设计模式之工厂模式(factory)

工厂模式

需要演示的pojo

public interface IProduct {

    void use();
}

public class Product implements IProduct{
    @Override
    public void use() {
        System.out.println("using ...");
    }
}

public class Product2 implements IProduct{
    @Override
    public void use() {
        System.out.println("using2 ...");
    }
}

简单工厂

负责创建的对象较少
客户端只需要传入工厂的参数,对于创建的对象逻辑不需要关心
不适用扩展

public class SimpleFactory {

    public IProduct create(Class clazz){

        try {
            if (!(null == clazz)){
                return (IProduct) clazz.newInstance();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        SimpleFactory simpleFactory = new SimpleFactory();
        IProduct iProduct = simpleFactory.create(Product.class);
        iProduct.use();
    }
}

工厂方法模式

提高扩展性,但是类也会增加,系统结构也会复杂,造成抽象难以理解
适合创建对象时需要大量代码的情况

接口

public interface IFactory {

    IProduct create();
}

工厂一

public class ProductFactory implements IFactory{
    @Override
    public IProduct create() {
        return new Product();
    }
}

工厂二

public class Product2Factory implements IFactory{
    @Override
    public IProduct create() {
        return new Product2();
    }
}

main

public class Main {

    public static void main(String[] args) {
        IFactory factory = new ProductFactory();
        factory.create().use();
        IFactory factory2 = new Product2Factory();
        factory2.create().use();
    }
}

抽象工厂模式

适合创建对象类型复杂的情况
不符合开闭原则,符合单一职能原则
强调一系列对象一起使用创建需要大量重复代码
增加系统复杂度,难以理解

父接口

public interface IFactory {

    IFruit createFruit();

    IVegetable createVegetable();

}

具体的产品类


public class Apple implements IFruit {}

public class Potato implements IVegetable{}

具体工厂

public class ChinaFactory implements IFactory{
    @Override
    public IFruit createFruit() {
        return new Apple();
    }

    @Override
    public IVegetable createVegetable() {
        return new Potato();
    }
}

public class AmericaFactory implements IFactory{
    @Override
    public IFruit createFruit() {
        return null;
    }

    @Override
    public IVegetable createVegetable() {
        return null;
    }
}

main

public class Main {

    public static void main(String[] args) {
        IFactory chinaFactory = new ChinaFactory();
        IFruit fruit = chinaFactory.createFruit();
        IFactory americaFactory = new AmericaFactory();
        americaFactory.createVegetable();
    }
}

设计模式之工厂模式(factory)
https://www.blaaair.com/archives/she-ji-mo-shi-zhi-gong-chang-mo-shi-factory
作者
Glo6f
发布于
2022年08月22日
许可协议