您的位置:首页 > 编程语言 > Python开发

[python实现设计模式]-1. 单例模式

2016-02-29 17:18 621 查看
近日草草看了python 面向对象的的一些东西。发现也是有点屌。然后呢。在地铁上就突然想起,能不能用python把23个设计模式给实现以下。就这样呢。设计模式中,最简单的一个就是 “单例模式”, 那么首先,就实现一下单例模式。那么根据个人的理解,很快就写出第一版。
# -*- coding: utf-8 -*-

class Singleton(object):

# 定义静态变量实例
__singleton = None

def __init__(self):
pass

@staticmethod
def get_instance():
if Singleton.__singleton is None:
Singleton.__singleton = Singleton()
return Singleton.__singleton
测试一下:
if __name__ == "__main__":
instance1 = Singleton.get_instance()
instance2 = Singleton.get_instance()

print id(instance1)
print id(instance2)

liutrumpdeMacBook-Air:singleton trump$ python Singleton
4419778640
4419778640在c#或java的设计模式中,我们通常是通过私有化类的构造函数来杀死类本身的繁殖能力,然后再给它安插一个共有的方法返回的单例。但是在python中,并没有办法来私有化构造函数.所以,并没有办法来阻止你干坏事。python的哲学是,没有人会阻止你干坏事。比如你想访问类的私有变量(__命名的变量), 也是ok的..
if __name__ == "__main__":
instance1 = Singleton.get_instance()
instance2 = Singleton.get_instance()

instance3 = Singleton()

print id(instance1)
print id(instance2)
print id(instance3)

执行结果:
liutrumpdeMacBook-Air:singleton trump$ python Singleton
4461824080
4461824080
4461824144
为了保证在多线程下线程安全性。我们在写单例模式时候, 通常使用双重锁定来检查实例是否存在。不了解的同学可以自行google 单例模式 双重检查锁定(double check locking).
# -*- coding: utf-8 -*-
import threading

Lock = threading.Lock()

class Singleton(object):

# 定义静态变量实例
__singleton = None

def __init__(self):
pass

@staticmethod
def get_instance():
if Singleton.__singleton is None:
Singleton.__singleton = Singleton()
return Singleton.__singleton

@staticmethod
def get_instance_thread():
if Singleton.__singleton is None:
try:
Lock.acquire()
if Singleton.__singleton is None:
Singleton.__singleton = Singleton()
finally:
Lock.release()

return Singleton.__singleton

if __name__ == "__main__":
instance1 = Singleton.get_instance()
instance2 = Singleton.get_instance()

instance3 = Singleton()

print id(instance1)
print id(instance2)
print id(instance3)

instance4 = Singleton.get_instance_thread()
instance5 = Singleton.get_instance_thread()

print id(instance4)
print id(instance5)

运行结果:

4335606992
4335606992
4335645008
4335606992
4335606992
另外,c#和java还有一种饿汉式的实现,就是静态成员在一开始就调用静态构造函数来实例化自身。遗憾的是,我在python下试了试。发现行不通。。好,第一个最简单的设计模式的python实现就到这里。to be continued.
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: