码迷,mamicode.com
首页 > 其他好文 > 详细

<人人都懂设计模式>-单例模式

时间:2019-08-11 20:55:09      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:RoCE   elf   tor   test   color   col   instance   none   als   

这个模式,我还是了解的。

书上用了三种不同的方法。

class Singleton1:
    # 单例实现方式1
    __instance = None
    __is_first_init = False

    def __new__(cls, name):
        if not cls.__instance:
            Singleton1.__instance = super().__new__(cls)
        return cls.__instance

    def __init__(self, name):
        if not self.__is_first_init:
            self.__name = name
        self.__is_first_init = True

    def get_name(self):
        return self.__name


tony = Singleton1(Tony)
karry = Singleton1(karry)
print(tony.get_name(), karry.get_name())
print(id(tony), id(karry))
print(tony == karry)
print("=======单例实现方式1========")


class Singleton2(type):
    # 单例实现方式2
    def __init__(cls, what, bases=None, dict=None):
        super().__init__(what, bases, dict)
        cls._instance = None

    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__call__(*args, **kwargs)
        return cls._instance


class CustomClass(metaclass=Singleton2):
    def __init__(self, name):
        self.__name = name

    def get_name(self):
        return self.__name


tony = CustomClass(Tony)
karry = CustomClass(karry)
print(tony.get_name(), karry.get_name())
print(id(tony), id(karry))
print(tony == karry)
print("=======单例实现方式2========")


def singleton_decorator(cls, *args, **kwargs):
    instance = {}

    def wrapper_singleton(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]

    return wrapper_singleton


@singleton_decorator
class Singleton3:
    # 单例实现方式2
    def __init__(self, name):
        self.__name = name

    def get_name(self):
        return self.__name


tony = Singleton3(Tony)
karry = Singleton3(karry)
print(tony.get_name(), karry.get_name())
print(id(tony), id(karry))
print(tony == karry)
print("=======单例实现方式3========")
C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test1/test.py
Tony Tony
39257648 39257648
True
=======单例实现方式1========
Tony Tony
39257984 39257984
True
=======单例实现方式2========
Tony Tony
39257928 39257928
True
=======单例实现方式3========

Process finished with exit code 0

 

<人人都懂设计模式>-单例模式

标签:RoCE   elf   tor   test   color   col   instance   none   als   

原文地址:https://www.cnblogs.com/aguncn/p/11336409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!