python24种设计模式

请看大王的表演

 

1.单例模式

"""
单例模式:就是项目从头到尾只会创建一个对象;

解析:就是判断对象存在吗,不存在则创建

原理:类实例化,会走new方法。

"""
class A():
    __obj = None
    def __new__(cls, *args, **kwargs):
        if not cls.__obj:
            cls.__obj = object.__new__(cls)
        return cls.__obj

def fun():
    a = A()
    print(id(a))

# 测试代码啊
from threading import Thread
for i in range(500):
    t = Thread(target=fun)
    t.start()
View Code

 2.工厂模式

"""
工厂模式:就是一个工厂,你告诉我吉利,我就会给你创建吉利,我不会让你看到是怎么创建的;

这个要求对象内部属性和方法都是一样的。
"""

class CarFactory():
    def create(self,obj):
        obj.create()

class CarA():
    def create(self):
        print("创建A型号车,ID为99")

class CarB():
    def create(self):
        print("创建B型号车,ID为99")

if __name__ == "__main__":
    # 创建一个工厂对象
    carFactory = CarFactory()

    # 生产车A
    carA = CarA()
    carFactory.create(carA)
    # 生产车B
    carB = CarB()
    carFactory.create(carB)
View Code

 3.建造者模式

"""
建造者模式模式:我认为是 对调用工厂模式的封装

这个要求对象内部属性和方法都是一样的。
"""

class CarFactory():
    def create(self,obj):
        obj.create()

class CarA():
    def create(self):
        print("创建A型号车,ID为99")

class CarB():
    def create(self):
        print("创建B型号车,ID为99")


def initCreate():
    # 创建一个工厂对象
    carFactory = CarFactory()

    # 生产车A
    carA = CarA()
    carFactory.create(carA)
    # 生产车B
    carB = CarB()
    carFactory.create(carB)
    
if __name__ == "__main__":
    initCreate()
View Code

 4.适配器模式

"""
适配器类:
是为了不让用户看到这个类,所以需要对这个类进行封装一下;
男人类一代隐身
男人类二代继承一代


这个和工厂的模式的区别:

工厂模式:用工厂类去 适配 所有的类
适配器模式:用一个二代类 适配 其中一个类

"""

# 基类
class People():
    pass

# 想让他看见这个类
class Woman(People):
    def __init__(self,name):
        self.name = name

    def eat(self):
        print(f"女人在吃饭")

# 1.1不想让他们看到这个类,
class Man(People):
    def __init__(self,name):
        self.name = name

    def eat(self):
        print(f"男人在吃饭")
#1.2需要写一个类对他重写一下
class TranslatMan(People):
    obj = None
    def __init__(self,name):
        self.obj = Man(name)

    def eat(self):
        self.obj.eat()

if __name__ == "__main__":
    woman = Woman("小琴")
    woman.eat()
    translatMan = TranslatMan("木木")
    translatMan.eat()
View Code

 

posted @ 2021-09-20 15:01    阅读(58)  评论(0编辑  收藏  举报