定义:
抽象工厂模式提供一个接口,用于创建相关或者依赖对象的家族,而不需要明确指定具体类。
抽象工厂允许客户端使用抽象的接口来创建一组相关的产品,而不需要关系实际产出的具体产品是什么。这样一来,客户就可以从具体的产品中被解耦。
示例代码:
Fruit.java
package com.designPattern.abstractFactory; /*** * * @author liuzhihu * */ public interface Fruit { /*** * 定义吃水果的方法 */ public void eatFruit(); }
Apple.java
package com.designPattern.abstractFactory; /*** * * @author liuzhihu * */ public abstract class Apple implements Fruit { public abstract void eatFruit(); }
Banana.java
package com.designPattern.abstractFactory; /*** * * @author liuzhihu * */ public abstract class Banana implements Fruit { public abstract void eatFruit(); }
NorthApple.java
package com.designPattern.abstractFactory; public class NorthApple extends Apple { @Override public void eatFruit() { System.out.println("吃北方苹果。。。。。。"); } }
NorthBanana.java
package com.designPattern.abstractFactory; public class NorthBanana extends Banana { @Override public void eatFruit() { System.out.println("吃北方香蕉。。。。。。"); } }
SouthApple.java
package com.designPattern.abstractFactory; public class SouthApple extends Apple { @Override public void eatFruit() { System.out.println("吃南方苹果。。。。。。"); } }
SouthBanana.java
package com.designPattern.abstractFactory; public class SouthBanana extends Banana { @Override public void eatFruit() { System.out.println("吃南方香蕉。。。。。。"); } }
FruitFactory.java
package com.designPattern.abstractFactory; public abstract class FruitFactory { /*** * 采集水果 * * @param type * @return */ public abstract Fruit getFruit(String type); }
NorthFruitFactory.java
package com.designPattern.abstractFactory; public class NorthFruitFactory extends FruitFactory { @Override public Fruit getFruit(String type) { if ("Apple".equals(type)) { return new NorthApple(); } else if ("Banana".equals(type)) { return new NorthBanana(); } else { System.out.println("找不到对应的水果......"); return null; } } }
SouthFruitFactory.java
package com.designPattern.abstractFactory; public class SouthFruitFactory extends FruitFactory { @Override public Fruit getFruit(String type) { if ("Apple".equals(type)) { return new SouthApple(); } else if ("Banana".equals(type)) { return new SouthBanana(); } else { System.out.println("找不到对应的水果......"); return null; } } }
MainTest.java
package com.designPattern.abstractFactory; public class MainTest { public static void main(String[] args) { // 北方水果 NorthFruitFactory northFruitFactory = new NorthFruitFactory(); Fruit northApple = northFruitFactory.getFruit("Apple"); northApple.eatFruit(); Fruit northBanana = northFruitFactory.getFruit("Banana"); northBanana.eatFruit(); // 南方水果 SouthFruitFactory southFruitFactory = new SouthFruitFactory(); Fruit southApple = southFruitFactory.getFruit("Apple"); southApple.eatFruit(); Fruit southBanana = southFruitFactory.getFruit("Banana"); southBanana.eatFruit(); } }
优点
1、 抽象工厂隔离了具体类的生成,是的客户端不需要知道什么被创建。所有的具体工厂都实现了抽象工厂中定义的公共接口,因此只需要改变具体工厂的实例,就可以在某种程度上改变整个软件系统的行为。
2、 当一个产品族中的多个对象被设计成一起工作时,它能够保证客户端始终只使用同一个产品族中的对象。
缺点
添加新的行为时比较麻烦。如果需要添加一个新产品族对象时,需要更改接口及其下所有子类,这必然会带来很大的麻烦。