您的位置:首页 > 其它

抽象工厂模式

2016-12-25 18:08 441 查看
《android设计模式》读书笔记,若由侵权,请联系我删除,谢谢

一。定义

  为创建一组相关或者相互依赖的对象提供一个接口,而不需要指定它们的具体类。

二。使用场景

  一个对象族有相同的约束时可以使用抽象工厂模式,例如,android, ios ,windowphone下都有短信和拨号软件,两者都属于software软件,但是它们在不同的操作系统平台下,也不一样,这个时候可以考虑使用抽象工厂模式来产生android, ios ,windowphone下的短信和拨号软件。

三。代码实现

****************************************************************************

package com.yinazh.designpatter;

public interface ITire{

void tire();

}

public class NormalTire implements ITire{

public void tire(){

System.out.println("normal tire");

}

}

public class SpecialTire implements ITire{

public void tire(){

System.out.println("special tire");

}

}

public interface IEngine{

void engine();

}

public class DomesticEngine implements IEngine{

public void engine(){

System.out.println("DomesticEngine engine");

}

}

public class ImportEngine implements IEngine{

public void engine(){

System.out.println("import engine");

}

}

public abstract class CarFactory{

public abstract ITire createTire();

public abstract IEngine createEngine();

}

public class Product1 extends CarFactory{

public ITire createTire(){

return new NormalTire();

}

public IEngine createEngine(){

return new DomesticEngine();

}

}

public class Product2 extends CarFactory{

public ITire createTire(){

return new SpecialTire();

}

public IEngine createEngine(){

return new ImportEngine();

}

}

public class Client{

public static void main(String[] args){

CarFactory pro1 = new Product1();

pro1.createTire().tire();

pro1.createEngine().engine();

}

}

****************************************************************************

总结:

 优点:分离接口和实现,客户端使用抽象工厂来创建需要的对象,而客户端根本就不知道具体的实现是谁,客户端只是面向产品的接口编程而已,使其从具体的产品中解藕,同时基于接口与实现的分离,使抽象该工厂方法模式在切换产品类时,更加灵活

 缺点:类文件的爆炸性的增加,不太容易扩展新的产品类,因为每当增加一个产品类就需要修改抽象工厂,那么所有的具体工厂类均需会被修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: