工厂函数
代码语言:javascript
复制class CachedSpamManager2:
def init(self):
self._cache = weakref.WeakValueDictionary()
代码语言:javascript
复制def get_spam(self, name):
if name not in self._cache:
temp = Spam3._new(name) # Modified creation
self._cache[name] = temp
else:
temp = self._cache[name]
return temp
def clear(self):
self._cache.clear()
代码语言:javascript
复制class Spam3:
def init(self, *args, **kwargs):
raise RuntimeError("Can't instantiate directly")
代码语言:javascript
复制# Alternate constructor
@classmethod
def _new(cls, name):
self = cls.__new__(cls)
self.name = name
return self
或者
The class in question
代码语言:javascript
复制class Spam:
def init(self, name):
self.name = name
Caching support
代码语言:javascript
复制import weakref
_spam_cache = weakref.WeakValueDictionary()
def get_spam(name):
if name not in _spam_cache:
s = Spam(name)
_spam_cache[name] = s
else:
s = _spam_cache[name]
return s