其他分享
首页 > 其他分享> > 抽象工厂笔记

抽象工厂笔记

作者:互联网

定义

结构

例子

用于创建一系列关联的对象,要用抽象类作为工厂,设置好方法,但是具体创建什么样的对象留到子类去实现.

public abstract class AbstractFactory {
    abstract  Object factoryMethod(String type);
}

//两个实现类根据输入的字符串创建了不同的对象.
public class AbstractFactoryA extends AbstractFactory{
    @Override
    Object factoryMethod(String type) {
        Pizza pizza = null;
        if (type.equals("A"))
            pizza = new PizzaA();
        else if (type.equals("B"))
            pizza = new PizzaB();
        else if (type.equals("C"))
            pizza = new PizzaC();
        return pizza;
    }
}

public class AbstractFactoryB extends  AbstractFactory {
    @Override
    Object factoryMethod(String type) {
        Pizza pizza = null;
        if (type.equals("A"))
            pizza = new PizzaC();
        else if (type.equals("B"))
            pizza = new PizzaB();
        else if (type.equals("C"))
            pizza = new PizzaA();
        return pizza;
    }
}

都实现了工厂方法,但是根据传入对象的不同会产生不同的对象

public class PizzaStore {
   public static void main(String[] args) {
        AbstractFactory a=new AbstractFactoryA();
        AbstractFactory b=new AbstractFactoryB();

        PizzaStore store1 = new PizzaStore(a);
        Pizza pizza1 = store1.orderPizza("A1");

        PizzaStore store2= new PizzaStore(b);
        Pizza pizza2 = store2.orderPizza("A");
    }
   AbstractFactory factory;
    public PizzaStore(AbstractFactory f ){
        this.factory=f;
    }
    //点一个Pizza
    public Pizza orderPizza(String type){
        Pizza pizza =(Pizza)factory.factoryMethod(type);

        System.out.println(type);

        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();
        return null;
    }
}

标签:笔记,工厂,抽象,AbstractFactory,new,Pizza,type,public,pizza
来源: https://www.cnblogs.com/l1057618497/p/12435902.html