简介

设计模式就是一种编程套路,使用特定的套路得到特定的效果。

单例模式

优点

  • 节省内存
  • 节省创建对象的开销

代码

dl.py
class apple:
    pass
pingguo = apple()
设计模式-单例.py
from dl import pingguo
pg1 = pingguo
pg2 = pingguo
print(pg1)
print(pg2)

输出

<dl.apple object at 0x00000534D057A090>
<dl.apple object at 0x00000534D057A090>

工厂模式

优点

  • 大批量创建对象的时候有统一的入口,易于代码维护
  • 当发生修改,仅修改工厂类的创建方法即可
  • 符合现实世界的模式,即由工厂来制作产品(对象)

代码

class animal:
    pass
class dog(animal):
    pass
class cat(animal):
    pass
class pig(animal):
    pass
class animalFactory:
    def get_animal(self,animal_type:str):
        if animal_type == 'd':
            return dog()
        elif animal_type == 'c':
            return cat()
        elif animal_type == 'p':
            return pig()
dongwu = animalFactory()
gou = dongwu.get_animal('d')
mao = dongwu.get_animal('c')
zhu = dongwu.get_animal('p')
print(gou)
print(mao)
print(zhu)

输出

<__main__.dog object at 0x0000020BD057A210>
<__main__.cat object at 0x0000020BD057A390>
<__main__.pig object at 0x0000020BD057A510>
最后修改:2025 年 01 月 15 日
如果觉得我的文章对你有用,请随意赞赏