python面向对象之单例模式

单例模式

第一阶段:普通模式

NAME = 'PLF'
AGE = 18
class Foo:
    __instance = None

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

    @classmethod
    def func(cls):
        if cls.__instance:
            return cls.__instance

        obj = cls(NAME,AGE)
        cls.__instance = obj
        return  obj

one = Foo.func()
two = Foo.func()
three = Foo.func()
four = Foo.func()
print(id(one))
print(id(two))
print(id(three))
print(id(four))

1734533208384
1734533208384
1734533208384
1734533208384

总结:通过类属性保存创建的第一个对象,之后对类属性进行判断,类属性有值则一直沿用类属性的值(对象),没有则创建。

第二阶段:进阶

NAME = 'PLF'
AGE = 18
def deco(cls):
    cls.__instance = cls(NAME,AGE)
    def wrapper(*args,**kwargs):
        if len(args) == 0 and len(kwargs) == 0:
            return cls.__instance
        res = cls(*args,**kwargs)
        return res
    return wrapper

@deco
class Foo:
    __instance = None
    def __init__(self,name,age):
        self.name = name
        self.age = age

ori = Foo() # Foo() = wrapper()	,没有加参数使用默认初始化
print(ori.name,ori.age)		

one = Foo('LT',100)     # 用户添加参数,则使用用户的参数进行初始化,不使用
print(one.name,one.age)
PLF 18
LT 100

第三阶段:最正宗的模式

NAME = 'PLF'
AGE = 18
class Foo(type):
    def __init__(self,class_name,class_bases,class_dict):
        super().__init__(class_name,class_bases,class_dict)
        self.instance = self(NAME,AGE)

    def __call__(self, *args, **kwargs):
        if self.instance:
            return self.instance
        obj = object.__new__(self)
        self.__init__(obj,*args,**kwargs)
        return obj


class Person(metaclass=Foo):
    instance = None
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def run(self):
        print("run")

    def eat(self):
        print("eat")

one = Person('zhangsan',20)
two = Person()
three = Person()
print(one)
print(two)
print(three)
<__main__.Person object at 0x000002A4FC2741D0>
<__main__.Person object at 0x000002A4FC2741D0>
<__main__.Person object at 0x000002A4FC2741D0>

通过类属性将我们自己的实例对象保留下来,之后再创建就一直使用类属性中的实例对象

posted @ 2019-06-21 19:20  Hello_Jack  阅读(154)  评论(0编辑  收藏  举报
# 页脚html代码 /*头部导航栏*/ #navigator { font-size:15px; border-bottom: 1px solid #ededed; border-top: 1px solid #ededed; height: 60px;/*导航栏高度,原始50*/ clear: both; margin-top: 25px; } /*导航栏设置,可以自定义导航栏的目录*/ #navList { min-height: 35px; float: left; } #navList li { /*每一个栏目节点*/ float: left; margin: 0 5px 0 0; /*这里原来是0 40px 0 0 */ } #navList a { /*栏目文字的格式*/ display: block; width: 5em; height: 22px; float: left; text-align: center; padding-top: 19px; }