设计模式之-抽象工厂模式VS简单工厂模式(python)

来源:互联网 发布:天刀少女捏脸数据下载 编辑:程序博客网 时间:2024/05/22 10:14

从某种成度上说抽象工厂模式就是简单工厂模式的工厂模式。工厂模式使用依赖和继承产生新的对象,而抽象工厂模式跟多的是以组合方式产生新的类。

简单工厂模式的结构如下图:



简单工厂模式示例代码:

#!/usr/bin/env python# -*- coding: utf-8 _*__#implementation of the simple factory pattern import randomclass 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@staticmethoddef shapeFactory(type):#return eval(type + "0")if type == "Circle":return Circle()if type == "Square":return Square()assert 0 , "Bad shape creation: " + typeclass 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@staticmethoddef colorFactory(type):#return eval(type + "0")if type == "Red":return Red()if type == "Green":return Green()assert 0 , "Bad color creation: " + typeclass 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()
0 0