代码改变世界

简单工厂模式

2019-02-25 17:17  剑动情缥缈  阅读(130)  评论(0编辑  收藏  举报

1.基本概念

  • 又叫做静态方法模式,因为包含了一个静态方法
  • 工厂用来生产产品
  • 解决的问题:将类的实例化操作与类使用者使用类的操作分开,使用者不需要知道具体参数就可以实例化所需要的产品类,从而避免在客户端指定,实现了解耦
  • UML类图:

  

  

2.代码实现

package com.chengjie;

interface Product {
    void show();
}

class ProductA implements Product {
    @Override
    public void show() {
        System.out.println("ProductA.show() is called!");
    }
}

class ProductB implements Product {
    @Override
    public void show() {
        System.out.println("ProductB.show() is called!");
    }
}

class ProductC implements Product {
    @Override
    public void show() {
        System.out.println("ProductC.show() is called!");
    }
}

class Factory {
    public static Product createProduct(String type) {
        switch (type) {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            case "C":
                return new ProductC();
            default:
                return null;
        }
    }
}

public class TestSimpleFactoryPattern {
    public static void main(String[] args) {
        Factory.createProduct("A").show();
        Factory.createProduct("B").show();
        Factory.createProduct("C").show();
        Factory.createProduct("D").show();
    }
}
View Code

3.优点

  • 将创建对象工作与使用对象工作分开,使用者不必关心累的创建过程,实现了解耦

4.缺点

  • 工厂类集中了所有实例(产品)的创建逻辑,一旦这个工厂不能正常工作,整个系统都会受到影响;
  • 违背“开放 - 关闭原则”,一旦添加新产品就不得不修改工厂类的逻辑,这样就会造成工厂逻辑过于复杂。
  • 简单工厂模式由于使用了静态工厂方法,静态方法不能被继承和重写,会造成工厂角色无法形成基于继承的等级结构。

5.应用场景

  • 客户如果只知道传入工厂类的参数,对于如何创建对象的逻辑不关心时;
  • 当工厂类负责创建的对象(具体产品)比较少时。

6.参考链接

  https://www.jianshu.com/p/e55fbddc071c