python设计模式之工厂模式(Factory Pattern)

网友投稿 932 2022-08-31

python设计模式之工厂模式(Factory Pattern)

python设计模式之工厂模式(Factory Pattern)

工厂模式的本质就是用工厂方法代替new操作创建一种实例化对象的方式.

这里专门定义一个Operation类作为父类,加减乘除运算类继承Operation类,OperationFactory类用来决定什么时候创建对应的类

import randomfrom typing import Typeclass Pet: def __init__(self, name: str) -> None: self.name = name def speak(self) -> None: raise NotImplementedError def __str__(self) -> str: raise NotImplementedErrorclass Dog(Pet): def speak(self) -> None: print("woof") def __str__(self) -> str: return f"Dog<{self.name}>"class Cat(Pet): def speak(self) -> None: print("meow") def __str__(self) -> str: return f"Cat<{self.name}>"class PetShop: """A pet shop""" def __init__(self, animal_factory: Type[Pet]) -> None: """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def buy_pet(self, name: str) -> Pet: """Creates and shows a pet using the abstract factory""" pet = self.pet_factory(name) print(f"Here is your lovely {pet}") return pet# Additional factories:# Create a random animaldef random_animal(name: str) -> Pet: """Let's be dynamic!""" return random.choice([Dog, Cat])(name)if __name__ == '__main__': cat_shop = PetShop(Cat) pet = cat_shop.buy_pet("Lucy") pet.speak() shop = PetShop(random_animal) for name in ["Max", "Jack", "Buddy"]: pet = shop.buy_pet(name) pet.speak() print("=" * 20)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:深度学习论文:Dynamic ReLU及其PyTorch实现
下一篇:Go语言中如何开启 TCP keepalive?(go语言官方教程)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~