classShape(object):def__init__(self):passdefdraw(self):passclassTriangle(Shape):def__init__(self):
print("I am a triangle")
defdraw(self):
print("I am drawing triangle")
classRectangle(Shape):def__init__(self):
print("I am a rectnagle")
defdraw(self):
print("I am drawing triangle")
classTrapezoid(Shape):def__init__(self):
print("I am a trapezoid")
defdraw(self):
print("I am drawing triangle")
classDiamond(Shape):def__init__(self):
print("I am a diamond")
defdraw(self):
print("I am drawing triangle")
classShapeFactory(object):
shapes = {'triangle': Triangle, 'rectangle': Rectangle,
'trapezoid': Trapezoid, 'diamond': Diamond}
def__new__(cls, name):# 相当于工厂 生成实例if name in ShapeFactory.shapes.keys():
print("creating a new shape %s" % name)
return ShapeFactory.shapes[name]()
else:
print("creating a new shape %s" % name)
return Shape()
ShapeFactory('rectangle').draw() ## 相当于 Rectangle().draw()