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

设计模式九(单例模式,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: