parent
b15c7505f6
commit
fe94d8ed1b
@ -0,0 +1,33 @@
|
||||
# 创建对象是消耗资源的,如果发现对象已经存在,可以返回引用,不创造新对象 。设计模式中这个做法叫享元
|
||||
from cppy.cp_util import *
|
||||
|
||||
#享元类
|
||||
class WordFrequencyController():
|
||||
def __init__(self, controllertype,filepath ):
|
||||
word_list = extract_file_words(filepath)
|
||||
word_freq = get_frequencies(word_list)
|
||||
self.word_freq = sort_dict(word_freq)
|
||||
self.number = controllertype
|
||||
def print_word_freqs( self ):
|
||||
print_word_freqs( self.word_freq,self.number)
|
||||
|
||||
#享元工厂
|
||||
class WordFrequencyControllerFactory():
|
||||
def __init__(self):
|
||||
self.types = {}
|
||||
|
||||
def get_WordFrequencyController(self, number,testfilepath):
|
||||
if number not in self.types:
|
||||
self.types[number] = WordFrequencyController(number,testfilepath) # 创建新的对象
|
||||
print('new obj',number,'*'*30)
|
||||
else:
|
||||
print('ref obj','*'*30)
|
||||
return self.types[number] # 重复使用已存在的对象
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
factory = WordFrequencyControllerFactory()
|
||||
for number in [ 1,3,5,3,5,7 ]:
|
||||
WordFrequency = factory.get_WordFrequencyController(number,testfilepath)
|
||||
WordFrequency.print_word_freqs()
|
||||
|
Loading…
Reference in new issue