Python 设计模式 - 生成器模式

  • 简述

    Builder Pattern 是一种独特的设计模式,它有助于使用简单的对象构建复杂的对象并使用算法方法。这种设计模式属于创造模式的范畴。在此设计模式中,构建器类逐步构建最终对象。此构建器独立于其他对象。

    生成器模式的优点

    • 它在类创建的指定对象的构造和表示之间提供了清晰的分离和独特的层。
    • 它可以更好地控制所创建模式的构建过程。
    • 它为更改对象的内部表示提供了完美的场景。
  • 如何实现生成器模式?

    在本节中,我们将学习如何实现构建器模式。
    
    class Director:
       __builder = None
       
       def setBuilder(self, builder):
          self.__builder = builder
       
       def getCar(self):
          car = Car()
          
          # First goes the body
          body = self.__builder.getBody()
          car.setBody(body)
          
          # Then engine
          engine = self.__builder.getEngine()
          car.setEngine(engine)
          
          # And four wheels
          i = 0
          while i < 4:
             wheel = self.__builder.getWheel()
             car.attachWheel(wheel)
             i += 1
          return car
    # The whole product
    class Car:
       def __init__(self):
          self.__wheels = list()
          self.__engine = None
          self.__body = None
       def setBody(self, body):
          self.__body = body
       def attachWheel(self, wheel):
          self.__wheels.append(wheel)
       def setEngine(self, engine):
          self.__engine = engine
       def specification(self):
          print "body: %s" % self.__body.shape
          print "engine horsepower: %d" % self.__engine.horsepower
          print "tire size: %d\'" % self.__wheels[0].size
    class Builder:
          def getWheel(self): pass
          def getEngine(self): pass
          def getBody(self): pass
    class JeepBuilder(Builder):
       
       def getWheel(self):
          wheel = Wheel()
          wheel.size = 22
          return wheel
       
       def getEngine(self):
          engine = Engine()
          engine.horsepower = 400
          return engine
       
       def getBody(self):
          body = Body()
          body.shape = "SUV"
          return body
    # Car parts
    class Wheel:
       size = None
    class Engine:
       horsepower = None
    class Body:
       shape = None
    def main():
       jeepBuilder = JeepBuilder() # initializing the class
       
       director = Director()
       
       # Build Jeep
       print "Jeep"
       director.setBuilder(jeepBuilder)
       jeep = director.getCar()
       jeep.specification()
       print ""
    if __name__ == "__main__":
       main()
    

    输出

    上述程序生成以下输出 -
    生成器模式