python中的设计模式

版权声明:本文为小盒子原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35393693/article/details/83752304

简单工厂模式:

class AppleCake(object):
    def __init__(self, weidao="苹果味道"):
        self.taste = weidao


class OrangeCake(object):
    def __init__(self, weidao="橘子味道"):
        self.taste = weidao


class CakeFactory(object):
    def createCake(self, weidao):
        if weidao == "橘子":
            cake = OrangeCake()
        elif weidao == "苹果":
            cake = AppleCake()
        return cake


class CakeStore(object):
    def __init__(self):
        self.factory = CakeFactory()

    def taste(self, weidao):
        cake = self.factory.createCake(weidao)
        print("------品尝味道:%s----"%cake.taste)


a = CakeStore()
a.taste("橘子")

通过__new__方法创建对象:

class Test(object):

    #初始化的功能
    #往往是完成对象的属性设置
    def __init__(self):
        self.num = 100
        print("-----init----")
        print(self)

    #完成创建一个对象
    #当a=Test()执行的时候,是先调用__new__方法完成创建对象,然后会紧接着
    #调用__init__方法,完成初始化的功能
    def __new__(cls):
        print("----new-----")
        print(cls)
        return super().__new__(cls)

    #def __str__(self):
    #   return "xxxxxx"


a = Test()
print(a.num)
print(a)

单例模式:

class Singleton(object):
    
    __instance = None

    def __new__(cls):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
        return cls.__instance


a = Singleton()
print(a)
b = Singleton()
print(b)

猜你喜欢

转载自blog.csdn.net/qq_35393693/article/details/83752304
今日推荐