Python中的建造者模式是一種創建復雜對象的設計模式,它允許您將創建對象的過程分解成多個步驟,從而使代碼更加靈活和可維護。以下是一個示例,說明如何在Python中實現建造者模式:
class Computer: def __init__(self): self._motherboard = None self._processor = None self._memory = None def set_motherboard(self, motherboard): self._motherboard = motherboard def set_processor(self, processor): self._processor = processor def set_memory(self, memory): self._memory = memory class ComputerBuilder: def __init__(self): self._computer = Computer() def build_motherboard(self): self._computer.set_motherboard('Motherboard') return self def build_processor(self): self._computer.set_processor('Processor') return self def build_memory(self): self._computer.set_memory('Memory') return self def get_computer(self): return self._computer class Director: def __init__(self, builder): self._builder = builder def construct(self): self._builder.build_motherboard().build_processor().build_memory() builder = ComputerBuilder() director = Director(builder) director.construct() computer = builder.get_computer() print(f'Motherboard: {computer._motherboard}') print(f'Processor: {computer._processor}') print(f'Memory: {computer._memory}')
上述代碼中,首先定義了一個Computer類,用于存儲要建造的對象。接下來定義了一個ComputerBuilder類,通過該類中的方法來構建Computer對象。Director類則用于安排構建步驟。最后,我們創建一個ComputerBuilder對象并將其傳遞給Director對象。將所有的構建步驟提交給Director后,我們可以從ComputerBuilder對象中檢索最終構建的Computer對象。
上一篇python 建立長連接
下一篇docker入門看啥書