Last active
December 26, 2015 12:49
-
-
Save meganehouser/7153733 to your computer and use it in GitHub Desktop.
Pythonのレジストリパターン実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Registry(object): | |
instance = None | |
@classmethod | |
def initialize(cls): | |
cls.instance = Registry() | |
def __init__(self): | |
self.data = 'Hello World' | |
@classmethod | |
def get_data(cls): | |
if not cls.instance: | |
cls.instance = Registry() | |
return cls.instance.data | |
import threading | |
class ThreadRegistry(object): | |
# threding.local()のデータはスコープを抜けると直ちにデストラクタが呼ばれる | |
thread_local = threading.local() | |
@classmethod | |
def get_instance(cls): | |
return cls.thread_local.instance | |
@classmethod | |
def initialize(cls, data): | |
if not getattr(cls.thread_local, 'instance', None): | |
cls.thread_local.instance = ThreadRegistry(data) | |
def __init__(self, data): | |
self.data = data | |
def get_data(self): | |
return self.data | |
if __name__ == '__main__': | |
ThreadRegistry.initialize('thread 001') | |
def call_thread(data): | |
ThreadRegistry.initialize(data) | |
for _ in range(20): | |
print(ThreadRegistry.get_instance().get_data()) | |
th = threading.Thread(target=call_thread, args=['thread 002']) | |
th.start() | |
for _ in range(20): | |
print(ThreadRegistry.get_instance().get_data()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment