構建器(Builder)設計模式


構建器(Builder)模式是一種獨特的設計模式,它有助於使用簡單物件構建複雜物件並使用演算法。 這種設計模式屬於建立型模式。 在這種設計模式中,構建器類逐步構建最終物件。 該構建器獨立於其他物件。

構建器(Builder)模式的優點

  • 它提供了清晰的分離和獨特的層次,可以在構建和表示由類建立的指定物件之間進行表示。
  • 它可以更好地控制所建模式的實現過程。
  • 它提供了改變物件內部表示的場景。

如何實現構建器模式?

在本節中,我們將學習如何實現構建器模式。參考以下實現程式碼 -

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()

執行上面程式,得到以下輸出結果 -