Copyright © 2022-2024 aizws.net · 网站版本: v1.2.6·内部版本: v1.23.3·
页面加载耗时 0.00 毫秒·物理内存 63.3MB ·虚拟内存 1300.0MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
Builder Pattern是一种独特的设计模式,该模式有助于使用简单对象构建复杂对象并使用算法方法。该设计模式属于创作模式类别。在此设计模式中,构建器类按逐步过程构建最终对象。此构建器独立于其他对象。
在本节中,我们将学习如何实现构建器模式。
# Filename : example.py # Date : 2020-08-22 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() director = Director() # Build Jeep print("Jeep") director.setBuilder(jeepBuilder) jeep = director.getCar() jeep.specification() print("") if __name__ == "__main__": main()
上面的程序生成以下输出-
Jeep body: SUV engine horsepower: 400 tire size: 22
原型设计模式有助于隐藏类创建的实例的复杂性。现有对象的概念与从头创建的新对象的概念不同。如果需要,新复制的对象的属性可能会有一些更改。这种方法可以节省开发产品所需的时间和资源。 1. 如何实现原型模式?现在 ...