设计模式九(单例模式,python语言实现)
2012-12-11 13:43
676 查看
基本知识请参考相关书籍,这里直接给实例
#源代码 # -*- coding: utf-8 -*- ####################################################### # # Singleton.py # Python implementation of the Class Singleton # Generated by Enterprise Architect # Created on: 11-十二�2012 10:02:17 # ####################################################### from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future_builtins import * import sys from PySide.QtCore import * from PySide.QtGui import * import threading class Singleton(object): """This class (a) defines an Instance operation that lets clients access its unique instance, and (b) may be responsible for creating its own unique instance. """ __instance=None __mutex=threading.Lock() def __new__(cls, name): if cls.__instance==None: cls.__mutex.acquire() if cls.__instance==None: cls.__instance=super(Singleton, cls).__new__(cls) cls.__instance.init(name) pass cls.__mutex.release() pass return cls.__instance def init(self,name): super(Singleton,self).__init__() self.name=name pass def SetName(self,name): self.name=name; pass def GetName(self): return self.name #客户端 #客户端 if(__name__=="__main__"): singleton1=Singleton("hello") singleton2=Singleton("world") if singleton1 is singleton2: print ('they are the same object') #运行结果 they are the same object
相关文章推荐
- 设计模式八(原型模式,python语言实现)
- 设计模式十一(桥接模式,python 语言实现)
- 设计模式十七(状态模式,python语言实现)
- 设计模式十(适配器模式,python语言实现)
- 设计模式十四(享元模式flyweight,python语言实现)
- 设计模式十八(观察者模式,python语言实现)
- 设计模式十三(外观模式,python语言实现)
- 设计模式十九(中介者模式,python语言实现)
- 设计模式十二(组合模式,python语言实现)
- java语言实现结构型设计模式—适配器模式
- 23种设计模式之python实现--Facade模式
- 23种设计模式之python实现--State模式
- 23种设计模式之python实现--Memento模式
- 设计模式四(装饰模式,采用python 实现)
- 二十三种设计模式及其python实现
- 二十三种设计模式及其python实现
- 大白话讲解设计模式之:代理模式 Java语言实现
- 23种设计模式之python实现--总结
- 设计模式之单例模式——Python实现
- 设计模式十六(职责链模式,python实现)