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

08 设计模式

时间:2016-06-27 12:06:45      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

1. 单例模式

单例,顾名思义单个实例

练习

class Foo:
    instance = None # 定义静态字段
    def __init__(self, name):
        self.name = name

    @classmethod
    def get_instance(cls):
        # cls类名
        if cls.instance:
            # 如果cls.instance存在,直接返回
            return cls.instance
        else:
            # 如果cls.instance不存在,定义cls.instance并返回
            obj = cls(alex)
            cls.instance = obj
            return cls.instance

obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)
# 输出结果:内存地址相同

小结:单利模式存在的目的是保证当前内存中仅存在单个实例,避免内存浪费!!!

 

08 设计模式

标签:

原文地址:http://www.cnblogs.com/liangdalong/p/5619663.html

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