设计模式九(单例模式,python语言实现)

来源:互联网 发布:淘宝发布宝贝物流重量 编辑:程序博客网 时间:2024/06/06 18:14

基本知识请参考相关书籍,这里直接给实例

 

 

#源代码# -*- 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 divisionfrom __future__ import print_functionfrom __future__ import unicode_literalsfrom future_builtins import *       import sysfrom PySide.QtCore import *from PySide.QtGui import  *import threadingclass 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 


 

原创粉丝点击