从某种成度上说抽象工厂模式就是简单工厂模式的工厂模式。工厂模式使用依赖和继承产生新的对象,而抽象工厂模式跟多的是以组合方式产生新的类。
简单工厂模式的结构如下图:
简单工厂模式示例代码:
#!/usr/bin/env python
# -*- coding: utf-8 _*__
#implementation of the simple factory pattern
import random
class Shape(object):
# Create based on class name:
def factory(type):
#return eval(type + "()")
if type == "Circle": return Circle()
if type == "Square": return Square()
assert 0, "Bad shape creation: " + type
factory = staticmethod(factory)
class Circle(Shape):
def draw(self): print("Circle.draw")
def erase(self): print("Circle.erase")
class Square(Shape):
def draw(self): print("Square.draw")
def erase(self): print("Square.erase")
# Generate shape name strings:
def shapeNameGen(n):
types = Shape.__subclasses__()
for i in range(n):
yield random.choice(types).__name__
shapes = [ Shape.factory(i) for i in shapeNameGen(7)]
for shape in shapes:
shape.draw()
shape.erase()
抽象工厂模式的结构如下:
抽象工厂模式示例代码:
#!/usr/bin/env python
# -*- coding: utf-8 _*__
#implementation of the atbstract factory pattern
class AbstractFactory(object):
def getShape(slef):
return Shape()
def getColor(slef):
return Color()
class Shape(AbstractFactory):
#create based on class name
@staticmethod
def shapeFactory(type):
#return eval(type + "0")
if type == "Circle":
return Circle()
if type == "Square":
return Square()
assert 0 , "Bad shape creation: " + type
class Circle(Shape):
def __init__(self):
self.name = "Circle"
def draw(self):
print(self.name+" draw")
def erase(self):
print(self.name+" erase")
class Square(Shape):
def __init__(self):
self.name = "Square"
def draw(self):
print(self.name+' draw')
def erase(self):
print(self.name+" erase")
class Color(AbstractFactory):
#create based on class name
@staticmethod
def colorFactory(type):
#return eval(type + "0")
if type == "Red":
return Red()
if type == "Green":
return Green()
assert 0 , "Bad color creation: " + type
class Red(Color):
def __init__(self):
self.name = "Red"
def padding(self):
print(self.name+" padding")
def reset(self):
print(self.name+" reset")
class Green(Color):
def __init__(self):
self.name = "Green"
def padding(self):
print(self.name+" padding")
def reset(self):
print(self.name+" reset")
if __name__ == '__main__':
abstractFactory = AbstractFactory()
types = Shape.__subclasses__()
for type in types:
circle = abstractFactory.getShape().shapeFactory(type.__name__)
circle.draw()
circle.erase()
types = Color.__subclasses__()
for type in types:
color = abstractFactory.getColor().colorFactory(type.__name__)
color.padding()
color.reset()