23种设计模式介绍(Python示例讲解)(11)

2023-04-30 来源:飞速影视
下面是一个简单的 Python 实现,演示了如何使用建造者模式来构建一个包含多个部件的复杂对象(汽车):
from abc import ABC, abstractmethodclass CarBuilder(ABC): @abstractmethod def reset(self): pass @abstractmethod def set_seats(self, number_of_seats): pass @abstractmethod def set_engine(self, engine_power): pass @abstractmethod def set_trip_computer(self): pass @abstractmethod def set_gps(self): passclass Car: def __init__(self): self.seats = 0 self.engine_power = 0 self.trip_computer = False self.gps = False def __str__(self): return f"Car with {self.seats} seats, {self.engine_power} engine, trip computer: {self.trip_computer}, GPS: {self.gps}"class SportsCarBuilder(CarBuilder): def __init__(self): self.car = Car() def reset(self): self.car = Car() def set_seats(self, number_of_seats): self.car.seats = number_of_seats def set_engine(self, engine_power): self.car.engine_power = engine_power def set_trip_computer(self): self.car.trip_computer = True def set_gps(self): self.car.gps = True def get_car(self): return self.carclass Director: def __init__(self, builder): self.builder = builder def build_sports_car(self): self.builder.reset() self.builder.set_seats(2) self.builder.set_engine(300) self.builder.set_trip_computer() self.builder.set_gps() return self.builder.get_car()if __name__ == "__main__": sports_car_builder = SportsCarBuilder() director = Director(sports_car_builder) sports_car = director.build_sports_car() print(sports_car)
相关影视
合作伙伴
本站仅为学习交流之用,所有视频和图片均来自互联网收集而来,版权归原创者所有,本网站只提供web页面服务,并不提供资源存储,也不参与录制、上传
若本站收录的节目无意侵犯了贵司版权,请发邮件(我们会在3个工作日内删除侵权内容,谢谢。)

www.fs94.org-飞速影视 粤ICP备74369512号