建造者模式
建造者模式(Builder Pattern)是一种创建型设计模式,它用于创建复杂对象,将一个对象的构建与其表示分离,以便可以创建不同类型的对象,同时避免构造器参数列表的过长问题。该模式通常包括一个指导者(Director)和一个具体的建造者(Builder),指导者负责指导具体的建造者来构建对象。建造者模式的关键是按照正确的顺序设置属性和调用方法,以确保最终生成所需的复杂对象。这有助于提高代码的可维护性和可扩展性。
在这个示例中,我们将Computer
类和ComputerBuilder
接口定义为抽象基类,并使用abc
模块的abstractmethod
装饰器来标记抽象方法。具体的电脑类ConcreteComputer
继承自Computer
,并实现了抽象方法__str__
来定义电脑对象的字符串表示。
具体的建造者类ConcreteComputerBuilder
继承自ComputerBuilder
,并实现了所有的抽象方法,包括set_meat
方法,用于设置电脑的meat
属性。
客户端代码与之前类似,使用指导者来构建电脑对象,包括设置了meat
属性。这种结合abc
的方式确保了电脑和建造者的一致性,同时也提供了更好的代码规范和可维护性。
from abc import ABC, abstractmethod
# 定义电脑抽象基类
class Computer(ABC):
def __init__(self):
self.cpu = None
self.memory = None
self.hard_drive = None
self.graphics_card = None
self.meat = None
@abstractmethod
def __str__(self):
pass
# 定义电脑建造者接口
class ComputerBuilder(ABC):
@abstractmethod
def set_cpu(self, cpu):
pass
@abstractmethod
def set_memory(self, memory):
pass
@abstractmethod
def set_hard_drive(self, hard_drive):
pass
@abstractmethod
def set_graphics_card(self, graphics_card):
pass
@abstractmethod
def set_meat(self, meat):
pass
@abstractmethod
def build(self):
pass
# 具体的电脑类
class ConcreteComputer(Computer):
def __str__(self):
return f"CPU: {self.cpu}, Memory: {self.memory}, Hard Drive: {self.hard_drive}, Graphics Card: {self.graphics_card}, Meat: {self.meat}"
# 具体的电脑建造者
class ConcreteComputerBuilder(ComputerBuilder):
def __init__(self):
self.computer = ConcreteComputer()
def set_cpu(self, cpu):
self.computer.cpu = cpu
def set_memory(self, memory):
self.computer.memory = memory
def set_hard_drive(self, hard_drive):
self.computer.hard_drive = hard_drive
def set_graphics_card(self, graphics_card):
self.computer.graphics_card = graphics_card
def set_meat(self, meat):
self.computer.meat = meat
def build(self):
return self.computer
# 定义电脑指导者
class ComputerDirector:
def __init__(self, builder):
self.builder = builder
def construct(self):
self.builder.set_cpu("Intel Core i7")
self.builder.set_memory("16GB")
self.builder.set_hard_drive("1TB SSD")
self.builder.set_graphics_card("NVIDIA GeForce RTX 3080")
self.builder.set_meat("Beef")
return self.builder.build()
# 定义高端电脑指导者
class ComputerDirectorHighEnd:
def __init__(self, builder):
self.builder = builder
def construct(self):
self.builder.set_cpu("Intel Core i9")
self.builder.set_memory("64GB")
self.builder.set_hard_drive("10TB SSD")
self.builder.set_graphics_card("NVIDIA GeForce RTX 4090Ti")
self.builder.set_meat("Beef")
return self.builder.build()
# 客户端代码
if __name__ == "__main__":
builder = ConcreteComputerBuilder()
director = ComputerDirector(builder)
computer = director.construct()
print("构建的电脑信息:")
print(computer)
director = ComputerDirectorHighEnd(builder)
computer = director.construct()
print("构建的电脑信息:")
print(computer)