zoukankan      html  css  js  c++  java
  • 设计模式

    设计模式之单例模式

    #!/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__
  • 相关阅读:
    MT【319】分段递推数列
    MT【318】分式不等式双代换
    Centos7环境变量
    VI快捷键
    Centos7 开机自动运行命令
    Centos7 编辑本地DNS解析配置文件
    Centos7修改主机名
    xadmin 自定义过滤器选项
    Centos7网卡配置文件
    Centos7 挂载
  • 原文地址:https://www.cnblogs.com/yxy-linux/p/5630165.html
Copyright © 2011-2022 走看看