python_设计模式_四种方式实现单例

1. 装饰器函数实现单例设计模式

"""

实现思路:先将类传给cls,然后调用get_instance方法
"""


def singleton(cls):
    instances = {}

    def get_instance(*args, **kwargs):
        if cls not in instances:# cls 为instances中的一个键,该类的构造函数作为值
            instances[cls] = cls(*args, **kwargs) # 某类的构造方法
        return instances[cls]

    return get_instance


@singleton
class Order:
    def __init__(self, title, price):
        self.title = title
        self.price = price

    def save(self):
        print(f'保存订单{self.title}成功!')


@singleton
class OrderInfo:
    def __init__(self, order_id, good_id):
        self.order_id = order_id
        self.goods_id = good_id

    def save(self):
        print(f'保存订单{self.order_id}的详情{self.goods_id}成功!')


def save(*args):
    for obj in args:
        obj.save()


if __name__ == '__main__':
    o1 = Order('Phone7', 9000)
    o2 = Order('Lenvon 9000', 4500)

    oi1 = OrderInfo(1, '1110000')
    oi2 = OrderInfo(1, '1130000')

    save(o1, o2, oi1, oi2)

2. 基类方式实现单例设计


import json
import pickle


class Singleton:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):# _instance 为cls的一个实例属性
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance.sets = {}  # 单例的字典类型属性sets
        return cls._instance


class SingletonHashSet(Singleton):

    def add(self, key, value):
        self.sets[key] = value

    def exists(self, key):
        return key in self.sets

    def get(self, key):
        if key not in self.sets:
            raise KeyError(f'{key} not exisits')
        return self.sets[key]

    def remove(self, key):
        if self.exists(key):
            del self.sets[key]

    def __str__(self):
        return json.dumps(self.sets)


if __name__ == '__main__':
    app = SingletonHashSet()
    app.add('name', 'disen')
    app.add('age', 20)

    print(app)

    app2 = SingletonHashSet()
    app2.add('name2', 'jack')
    app2.add('age2', 18)

    print(app2)


3. 元类方式实现单例设计模式

"""
注意:
    python2写法:
        class Apple():
            __metaclass__=Singleton


    python3写法:
        class Apple(metaclass=Singleton):
"""


class Singleton(type):

    def __call__(cls, *args, **kwargs):
        print(args)
        print(kwargs)
        if not hasattr(cls, '_instance'):
        # cls 中一个实例属性_instance
            cls._instance = super().__call__(*args, **kwargs)

        return cls._instance


class Apple(metaclass=Singleton):
    def __init__(self, name):
        self.name = name


if __name__ == '__main__':
    a1 = Apple('jack')
    a2 = Apple('mack')

    print(a1.name, a2.name)
    print(a1 is a2)

4-----继承

class Singleton(object):
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls)
        return cls._instance


class SqlClient(Singleton):
    info = None

    def register(self, host, user, passwd):
        self.info = "{}--{}--{}".format(host, user, passwd)

继承父类的init,new魔术方法总结

  • 只要相同子类继承同一个单例父类,其id 均相同
  • init 魔术方法
1.父类名.__init__(self,*args,**kwargs)
2.super(子类名,self).__init__(*args,**kwargs)  # 注意init方法中的形参没有self,报错:TypeError: __init__() takes 1 positional arguments but 2 were given
3. 2的改动 super() 方法里头不用带参数
  • new 魔术方法
1.super(子类名,cls).__new__(cls《SEED》,*args,**kwargs)  # python 3.3+ 后,当子类覆盖父类的init方法和new方法,new方法不接受传入的初始化参数
    去掉SEED,报错,typeError,super.__new__(子类名),子类名 is not a subtype of a super  ?????????
    eg.
    	cls._instance = super(Singleton).__new__(cls, *args, **kw) #传入BUS的类,而不是Singleton
    	单例的子类BUS
3.1的改动 super() 方法里头不用带参数
    
2.父类名.__new__(cls)
cls._instance = super().__new__( 【cls,*args, **kwargs) # 去掉cls报错误 Object.new() not enought argument
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值