简单工厂设计模式

意图:

    定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。

适用性:
    
    当一个类不知道他所必须创建的对象的类的时候。
    当一个类希望有他的子类来指定他所创建的对象的时候
    当类将创建对象的职责委托给多个子类中的某一个。

class ShapeFactory(object):
    '''工厂类'''

    def getShape(self):
      return self.shape_name

class Circle(ShapeFactory):

  def __init__(self):
    self.shape_name = "Circle"
  def draw(self):
    print('draw circle')

class Rectangle(ShapeFactory):
  def __init__(self):
    self.shape_name = "Retangle"
  def draw(self):
    print('draw Rectangle')

class Shape(object):
  '''接口类,负责决定创建哪个ShapeFactory的子类'''
  def create(self, shape):
    if shape == 'Circle':
      return Circle()
    elif shape == 'Rectangle':
      return Rectangle()
    else:
      return None


fac = Shape()
obj = fac.create('Circle')
obj.draw()
obj.getShape()

优点:用户不需要修改代码

缺点:当用户需要添加新的运算类的时候,不仅需新加运算类,还需要修改工厂类,违反了开放封闭原则

原文地址:https://www.cnblogs.com/renfanzi/p/6009138.html