一、单例模式
#实习__init__函数之前会先执行__new__函数,在__new__中判断类是否有进行实例化 #如果有则使用之前实例化的数据进行实例化 class Singleton(object): def __init__(self): self.a =100 def __new__(cls, *args, **kwargs): if not hasattr(cls,'_instance'): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance a = Singleton() b = Singleton() print(a.a,b.a)
二、工厂模式
定义:定义一个用于创建对象的接口,让子类决定实例化哪个类。类图一般如下设计,产品类定义产品的公共属性和接口,工厂
类定义产品化的方式.
import random class PetShop(object): def __init__(self,animal_factory=None): # pet 宠物 factory 工厂 self.pet_factory = animal_factory def show_pet(self): pet = self.pet_factory.get_pet() print("this is a lovely", pet) print("it says",pet.speak()) print("it eats",self.pet_factory.get_food()) class Dog: def speak(self): return "Dog" def __str__(self): return "this is Dog" class Cat: def speak(self): return "Cat" def __str__(self): return "this is Cat" class CatFactory: def get_pet(self): return Cat() def get_food(self): return "cat food" class DogFactory: def get_pet(self): return Dog() def get_food(self): return "dog food" def get_factory(): return random.choice([DogFactory,CatFactory]) if __name__ == '__main__': shop = PetShop() # pet_factory 默认为None,后面延迟加载 shop.pet_factory = get_factory()() # 延迟加载,随机选择一个工厂然后实例出来一个对象给商店 shop.show_pet()
人生苦短,我用cnblog