角色:
抽象工厂角色:担任这个角色是模式的核心,他应该是与应用商业系统无关的。通常是Java接口或Java抽象类,其他的具体工厂类必须实现这个Java接口或继承这个Java抽象类。
具体工厂角色:这个角色直接在客户端的调用下创建产品的实例,这个角色含有选择合适的产品对象的逻辑,而这个逻辑是与应用系统商业逻辑紧密相关的。
抽象产品角色:这个角色是工厂模式所创建的对象的父类,或他们共同的接口。
具体产品角色:抽象工厂模式所创建的任何产品对象都是某一个具体产品类的实例。这是客户端最终需要的东西,其内部充满了商业逻辑。
类结构图:
水果抽象接口:
package com.design.abstractfactory; public interface Fruit { void fruitInfo(); }
蔬菜抽象接口:
package com.design.abstractfactory; public interface Vegetable { void vegetableInfo(); }
工厂抽象接口:
package com.design.abstractfactory; public interface Factory { Fruit createFruit(); Vegetable createVegetable(); }
具体类:北方水果
package com.design.abstractfactory; public class NorthFruit implements Fruit { @Override public void fruitInfo() { System.out.println("North-Apple"); } }
具体类:南方水果
package com.design.abstractfactory; public class SouthFruit implements Fruit { @Override public void fruitInfo() { System.out.println("South-Banana"); } }
具体类:北方蔬菜
package com.design.abstractfactory; public class NorthVegetable implements Vegetable { @Override public void vegetableInfo() { System.out.println("North-Tomato"); } }
具体类:南方蔬菜
package com.design.abstractfactory; public class SouthVegetable implements Vegetable { @Override public void vegetableInfo() { System.out.println("South-Taro"); } }
具体类:北方产品工厂
package com.design.abstractfactory; public class NorthProductFactory implements Factory { @Override public Fruit createFruit() { return new NorthFruit(); } @Override public Vegetable createVegetable() { return new NorthVegetable(); } }
具体类:南方产品工厂
package com.design.abstractfactory; public class SouthProductFactory implements Factory { @Override public Fruit createFruit() { return new SouthFruit(); } @Override public Vegetable createVegetable() { return new SouthVegetable(); } }
测试类:
package com.design.abstractfactory; public class Client { public static void main(String[] args){ Factory northFactory = new NorthProductFactory(); Factory southFactory = new SouthProductFactory(); System.out.println("北方产品:"); northFactory.createFruit().fruitInfo(); northFactory.createVegetable().vegetableInfo(); System.out.println("南方产品:"); southFactory.createFruit().fruitInfo(); southFactory.createVegetable().vegetableInfo(); } }
输出: