工厂模式实现了创建者和调用者的分离,使用专门的工厂类将选择实现类、创建对象进行统一的管理和控制。
# -*- coding: utf-8 -*-
"""
@Time : 2021/11/17 00:56
@Auth : yqq
@File :mypy02.py
"""
class CarFactory:
def create_car(self,brand):
if brand == "奔驰":
return Benz()
elif brand == "宝马":
return BMW()
elif brand == "比亚迪":
return BYD()
else:
return "未知品牌,不能创建"
class Benz:
pass
class BMW:
pass
class BYD:
pass
factory = CarFactory()
c1 = factory.create_car("奔驰")
c2 = factory.create_car("比亚迪")
c3 = factory.create_car("宝马")
print(c1)
print(c2)
print(c3)