GOF(group of four) 23 种设计模式
工厂模式
class CarFactory:
def create_car(self, brand):
if brand == "宝马":
return BMW()
elif brand == "奔驰":
return Benz()
elif brand == "比亚迪":
return BYD()
else:
print("不会造!!!")
class BMW:
pass
class Benz:
pass
class BYD:
pass
factory = CarFactory()
p1 = factory.create_car("宝马")
print(p1)
p2 = factory.create_car("奔驰")
print(p2)
p3 = factory.create_car("法拉利")
##########################################################
<__main__.BMW object at 0x0064EC30>
<__main__.Benz object at 0x0064ECF0>
不会造!!!
##########################################################
个人感觉:结构上更加清晰了。相当于总的公司接收订单,然后交付给各厂商完成各自的订单。
单例模式
class SingleMode:
__obj = None
__init__flag = True
def __new__(cls, *args, **kwargs):
if cls.__obj == None:
cls.__obj = object.__new__(cls)
return cls.__obj
def __init__(self, name):
if SingleMode.__init__flag:
print("init...")
self.name = name
SingleMode.__init__flag = False
a = SingleMode("aa")
b = SingleMode("bb")
print(a, b)
##############################################
init...
<__main__.SingleMode object at 0x002EF6B0> <__main__.SingleMode object at 0x002EF6B0>
##############################################
实现同步控制,没搞明白。。。