简单工厂模式
class CarStore(object): def order(self,car_type): return select_car_by_type(car_type) def select_car_by_type(car_type): if car_type == "丰田": return TOYOTA() elif car_type =="本田": return HONDA() elif car_type =="尼桑": return NISSAN() else: pass class Car(object): def move(self): print("车在移动") def stop(self): print("车已停止") def music(self): print("车播放音乐") class TOYOTA(Car): def __str__(self): return "这款车是丰田牌轿车!" class HONDA(Car): def __str__(self): return "这款车是本田牌轿车!" class NISSAN(Car): def __str__(self): return "这款车是尼桑牌轿车!" car_store = CarStore() car = car_store.order("丰田") print(car)
class CarStore(object): def __init__(self): self.factory = Factory() def order(self,car_type): return self.factory.select_car_by_type(car_type) class Factory(object): def select_car_by_type(self,car_type): if car_type == "丰田": return TOYOTA() elif car_type =="本田": return HONDA() elif car_type =="尼桑": return NISSAN() else: pass class Car(object): def move(self): print("车在移动") def stop(self): print("车已停止") def music(self): print("车播放音乐") class TOYOTA(Car): def __str__(self): return "这款车是丰田牌轿车!" class HONDA(Car): def __str__(self): return "这款车是本田牌轿车!" class NISSAN(Car): def __str__(self): return "这款车是尼桑牌轿车!" car_store = CarStore() car = car_store.order("丰田") print(car) car.move()
工厂方法模式:
__new__ 方法:
class Dog(object): def __init__(self): print("---init方法---") def __del__(self): print("---del方法---") def __str__(self): print("---str方法---") return "返回对象的描述信息" def __new__(cls): #cls是Dog指向的那个类对象 #print(id(cls)) print("---new方法---") return object.__new__(cls) #print(id(Dog)) xtq = Dog() print(xtq) ---new方法--- ---init方法--- ---str方法--- 返回对象的描述信息 ---del方法---
只初始化一次对象
class Dog(object): __instance = None #空 __init__flag = False def __new__(cls,name): if cls.__instance == None: cls.__instance = object.__new__(cls) return cls.__instance else: return cls.__instance def __init__(self,name): if self.__init__flag ==False: self.name = name self.__init__flag = True a = Dog("旺财") print(id(a)) print(a.name) b = Dog("笑天犬") print(id(b)) print(b.name)