1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 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()

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

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