抽象工厂模式:提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
抽象工厂允许客户使用抽象的接口来创建一组相关的产品,而不需要知道实际产出的具体产品是什么。
烤鱼之抽象工厂模式类图: 类A,B实现了接口TiaoLiao,分别是调料A,调料B。FactoryA,FactoryB是AbstractFactory的子类,通过create方法来实例化TiaoLiao。
TiaoLiao接口代码实现:
public interface TiaoLiao {}A类代码实现:
public class A implements TiaoLiao{ public A(){ System.out.PRintln("调料A"); }}B类代码实现:
public class B implements TiaoLiao{ public B(){ System.out.println("调料B"); }}AbstractFactory类代码实现:
public abstract class AbstractFactory { public abstract TiaoLiao create();}FactoryA类代码实现:
public class FactoryA extends AbstractFactory{ @Override public TiaoLiao create() { // TODO Auto-generated method stub return new A(); }}FactoryB类代码实现:
public class FactoryB extends AbstractFactory{ @Override public TiaoLiao create() { // TODO Auto-generated method stub return new B(); }}KaoYu类代码实现:
public class KaoYu { AbstractFactory abstractFactory; public KaoYu(AbstractFactory abstractFactory){ this.abstractFactory = abstractFactory; } public TiaoLiao orderFish(){ return abstractFactory.create(); }}测试类AbstractFactoryTest代码实现:
public class AbstractFactoryTest { public static void main(String[] args){ AbstractFactory abstractFactory = new FactoryA(); KaoYu kaoYu = new KaoYu(abstractFactory); kaoYu.orderFish(); AbstractFactory abstractFactory2 = new FactoryB(); KaoYu kaoYu2 = new KaoYu(abstractFactory2); kaoYu2.orderFish(); }}运行结果:
调料A调料B新闻热点
疑难解答