设计模式

设计模式之单例模式

#!/bin/bin/env python
# -*-coding:utf-8 -*-
# Author : rain
# 设计模式之单例模式

class Foo_singleton:
    __instance = None       # 静态私有字段

    def __init__(self, name):
        self.name = name

    def t_getinstance(self):
        print(self.name)
        return "test_instance"

    @classmethod            # 类方法
    def getinstance(cls):
        if cls.__instance:
            # 判断类字段是否有值,有值则说明已经创建过对象
            return cls.__instance
        else:
            # 创建实例
            obj = cls('rain')
            # 将实例赋值给静态私有类字段
            cls.__instance = obj
            print(obj.t_getinstance())
            # 返回值
            return cls.__instance

if __name__ == '__main__':
    Foo_singleton.getinstance()
    # 只在第一次创建实例的时候打印
    # rain
    # test_instance

    Foo_singleton.getinstance()
    # 并没有创建
class Foo:
    __instance = None

    def __init__(self):
        print("__init__")

    def __new__(cls, *args, **kwargs):
        print("__new__")
        if cls.__instance:
            return cls.__instance
        else:
            cls.__instance = super(Foo, cls).__new__(cls, *args)
        return cls.__instance


if __name__ == '__main__':
    foo = Foo()
    # __new__
    # __init__
__new__
原文地址:https://www.cnblogs.com/yxy-linux/p/5630165.html