Python设计模式----4.构建者模式
构建者模式:
将一个复杂对象的构造与表现进行分离,利用多个步骤进行创建,同一个构建过程可用于创建多个不同的表现
构建者模式一般由 Director(指挥官)和 Builder(建设者)构成
class Car: def __init__(self): self.money = None self.address = None self.car_name = None self.buy_time = None def __str__(self): return f'准备了{self.money}元,去{self.address}看看{self.car_name},还不错,买了,时间:{self.buy_time}' class CarBuilder: def __init__(self): self.car = Car() def ready_money(self, money): self.car.money = money return self def see_car(self, address): self.car.address = address return self def test_drive(self, car_name): self.car.car_name = car_name return self def buy_car(self, buy_time): self.car.buy_time = buy_time return self class Director: def __init__(self): self.builder = None def build(self, builder): self.builder = builder self.builder.ready_money('100').see_car('4s店').test_drive('单车').buy_car('2020.11.22') return self.builder.car if __name__ == '__main__': car_builder = CarBuilder() director = Director() car = director.build(car_builder) print(car)