python的單例模式

來源:互聯網
上載者:User

1.這裡介紹的python的單例模式有兩種方式,一種方式是win32event的CreateMutex來實現,另外就是定義一個全域變數

第一種實現方式可以參考這裡http://code.activestate.com/recipes/474070-creating-a-single-instance-application/

from win32event import CreateMutexfrom win32api import CloseHandle, GetLastErrorfrom winerror import ERROR_ALREADY_EXISTSclass singleinstance:    """ Limits application to single instance """    def __init__(self):        self.mutexname = "testmutex_{D0E858DF-985E-4907-B7FB-8D732C3FC3B9}"        self.mutex = CreateMutex(None, False, self.mutexname)        self.lasterror = GetLastError()        def aleradyrunning(self):        return (self.lasterror == ERROR_ALREADY_EXISTS)            def __del__(self):        if self.mutex:            CloseHandle(self.mutex)#---------------------------------------------## sample usage:#from singleinstance import singleinstancefrom sys import exit# do this at beginnig of your applicationmyapp = singleinstance()# check is another instance of same program runningif myapp.aleradyrunning():    print "Another instance of this program is already running"    exit(0)# not running, safe to continue...print "No another instance is running, can continue here"## end of http://code.activestate.com/recipes/474070/ }}}

2.對於方法2,網上的方法很多,這裡就簡單的摘抄一個,http://dev.firnow.com/course/1_web/webjs/200855/114357.html

 

代碼

class Logger(object):
log = None
@staticmethod
def new():
if not Logger.log:
Logger.log = Logger()
return Logger.log
def write(self, v):
print str(self), v

log1 = Logger.new()
log1.write("log1")

log2 = Logger.new()
log2.write("log2")

“”“
分析:很簡單的實現方法,把當前執行個體儲存起來,下次執行個體化時再返回以前的執行個體。但是在判斷的時候保證不了是安全執行緒的。放在這裡,先有個思路。
"""

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.