forked from p46318075/CodePattern
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.3 KiB
34 lines
1.3 KiB
# 创建对象是消耗资源的,如果发现对象已经存在,可以返回引用,不创造新对象 。设计模式中这个做法叫享元
|
|
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: ','*'*30,number)
|
|
else:
|
|
print('ref obj: ','*'*30,number)
|
|
return self.types[number] # 重复使用已存在的对象
|
|
|
|
|
|
if __name__ == "__main__":
|
|
factory = WordFrequencyControllerFactory()
|
|
for number in [ 1,3,5,3,5,7 ]:
|
|
WordFrequency = factory.get_WordFrequencyController(number,testfilepath)
|
|
# print(flush=True)
|
|
WordFrequency.print_word_freqs()
|
|
|