python版本的单例模式

 

# -*- coding:UTF-8 -*-


class Singleton(object):
    __instance = None

    # 堵死以直接实例化方式创建对象
    def __init__(self):
        raise ValueError('must get instance from method')

    @classmethod
    def get_instance(cls):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance


if __name__ == "__main__":
    s1 = Singleton.get_instance()
    s2 = Singleton.get_instance()

    if id(s1) == id(s2):
        print("s1与s2是相同的对象")

 

posted @ 2018-01-25 16:42  gjw  阅读(108)  评论(0)    收藏  举报