设计模式之简单工厂模式

简单工厂模式

1.简单工厂模式结构图

简单工厂模式结构图
2.示例代码:

public interface Product {
    void doSomething();
}

public class ProductA implements Product{
    @Override
    public void doSomething() {
        System.out.println("这是产品A!");
    }
}

public class ProductB implements Product{
    @Override
    public void doSomething() {
        System.out.println("这是产品B!");
    }
}


public class SimpleFactory {

    private int a = 1;
    private int b = 2;

    public Product makeProduct(int type) {
        Product product = null;
        if (a == type) {
            product = new ProductA();
        } else if (b == type) {
            product = new ProductB();
        }
        return product;
    }

    public Product makeProduct(String className) {
        Product product = null;
        if (null != className && className.trim() != ""){
            try {
                product = (Product)Class.forName(className).getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return product;
    }

    public Product makeProduct(Class<? extends Product> clazz) {
        Product product = null;
        if (null != clazz){
            try {
                product = clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return product;
    }
}
  1. 总结:

    优点:结构简单,调用方便;工厂和产品的职责区分明确.

    缺点:工厂类单一,若产品增多,则代码臃肿,违背高聚合原则.

posted @ 2021-04-11 18:41  justKen  阅读(39)  评论(0编辑  收藏  举报