简单工厂

2019-12-11  本文已影响0人  銗誨

意义

在创建对象时通过一个通用接口创建,以屏蔽细节;

好处

实现客户类和具体子类的解耦。一旦子类改变,只需修改具体子类以及工厂类。

具体操作

image.png

具体代码

接口

public interface Product {
}

具体子类

public class ProductChild1 implements Product{
}

具体子类

public class ProductChild2 implements Product {
}

工厂类

public class SimpleFactory {
    public Product createProduct(int type) {
        if (type == 1){
            return new ProductChild1();
        }else if (type == 2){
            return new ProductChild2();
        }
        else return null;
    }
}

客户类

public class SimpleF {
    public static void main(String[] args) {
        SimpleFactory simpleFactory = new SimpleFactory();
        Product product = simpleFactory.createProduct(1);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读