Python的工厂模式和单例模式

工厂模式:

解耦
定义类或方法,让其功能越单一越好

#!/usr/bin/python
#coding:utf-8
class Cake():
    def __init__(self,weidao="默认"):

        self.taste=weidao

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

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



class CakeStore(object):
    def taste(self,weidao):
        if weidao == "苹果":
            cake = AppleCake()
            print("------味道%s------"%cake.taste)
        elif weidao == "橘子":
	    cake = OrangeCake()
            print("---------味道%s------"%cake.taste)
haolilai = CakeStore()
haolilai.taste("橘子")

[root@server python]# python 工厂方法.py 
---------味道橘子------

在这个代码中如果我们想再增加一种口味的蛋糕就需要在CakeStore()这个类里面增加代码,在外面再写一个类,这样不太好

工厂方法:

class CakeFactory(object):
    def CreateCake(self,weidao):
        if weidao == "苹果":
            cake = AppleCake()
        elif weidao == "橘子":
            cake = OrangeCake()
        return cake  #这里一定要有返回值,因为我们需要这个函数的执行结果在另一个函数里面调用

class CakeStore(object):
    def __init__(self):
        self.factory = CakeFactory()
    def taste(self,weidao):
        cake = self.factory.CreateCake(weidao)
        print("-----品尝味道:%s-----"%cake.taste)
haolilai = CakeStore()
haolilai.taste("橘子")

[root@server python]# python 工厂方法.py 
-----品尝味道:橘子-----
                                                            

单例模式
__new__方法

class Test(object):
    #初始化功能,往往完成对象属性的设置
	def __init__(self):
        self.num = 100
        print("-------100------")
        print(self)
    #完成创建一个对象
    #当a = Test()执行的时候,是先调用__new__方法完成创建对象,然后紧接着调用__init__(),一般不重写new方法

    def __new__(cls):  
        print("---new--------")
        print(cls)
        return super().__new__(cls) #cls表示当前类,即创建一个当前类的对象。 返回创建的对象,这样__init__中的self就可以调用此对象。
    def __str__(self):
        return "hahah"


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

#!/usr/bin/python
#coding=utf-8

class Singleton(object):
    __instance = None  #类属性,可以通过类名去调用
    __first_init = False

    def __new__(cls,age,name):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)  #cls相当于类
        return cls.__instance

    def __init__(self,age,name):
        if not self.__first__init:
            self.age = age
            self.name = name
            Singleton.__first__init = True

a = Singleton(18,"haha")
b = Singleton(8,"hahah")

__new__方法总结:

  • 至少有一个参数cls,代表要实例化的类,此参数在实例化时由python解释器自动提供
  • 必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时需要特别注意,可以return父类__new__出俩的实例,或者是object的__new__出来的实例
  • __init__有一个参数self,就是这个__new__的返回实例,__init__在__new__的基础上可以完成其它初始化的动作,__init__不需要返回值
  • 我们可以将类比作制造商,__new__就是前期的原始材料的购买环节,__init__就是在原有材料的基础上加工、初始化商品环节。
#!/usr/bin/python4
#coding:utf-8

class Test(object):
    def __init__(self):
        self.num = 100
        print("---init---")
        print(self)
    def __new__(cls):
        print("---new---")
        print(cls)
        return super().__new__(cls)

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

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

在这里插入图片描述
#!/usr/bin/python
#coding=utf-8

class Singleton(object):
__instance = None #类属性,可以通过类名去调用
__first_init = False

def __new__(cls,age,name):
    if not cls.__instance:
        cls.__instance = object.__new__(cls)  #cls相当于类
    return cls.__instance

def __init__(self,age,name):
    if not self.__first__init:
        self.age = age
        self.name = name
        Singleton.__first__init = True

a = Singleton(18,"haha")
b = Singleton(8,"hahah")

单例控制:

#!/usr/bin/python 
#coding:utf-8
class singleton(object):
    __instance = None
    def __new__(cls):
        if cls.__instance == None:
            cls.__instance=object.__new__(cls)   #等价于(super).__new__(cls)
        return cls.__instance

a = singleton()
b = singleton()
print(a)
print(b)

在这里插入图片描述
在__init__部分完成初始化的控制,只初始化一次。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值