Python 设计模式之简单工厂模式

2019-11-24 / Java Python Design Pattern

 

simple-factory

 

# coding:utf-8


class Shape(object):
    def draw(self):
        raise NotImplementedError


class Circle(Shape):
    def draw(self):
        print("draw circle")


class Square(Shape):
    def draw(self):
        print("draw square")


class Rectangle(Shape):
    def draw(self):
        print('draw rectangle')


class ShapeFactory(object):
    def getShape(self, shape):
        if shape == 'Circle':
            return Circle()
        elif shape == 'Rectangle':
            return Rectangle()
        else:
            return None


fac = ShapeFactory()
obj = fac.getShape('Circle')
obj.draw()

优点: 客户端使用统一的代码进行创建不同类的实例。

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