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.

51 lines
2.5 KiB

9 months ago
'''
9 months ago
享元模式中对象被设计为可共享的被多个上下文使用而不必在每个上下文中都创建新的对象
9 months ago
如果我们有大量不同的词频分析需求有时需要词频前10的单词有时需要词频前20的单词有时还需要限定词汇的长度那就需要创建多个词频统计器每个词频统
9 months ago
计器都独立创建并存储其内部状态在这种情况下享元模式共享相同类型的词频统计器对象只需创建一个共享实例然后通过设置不同的参数个性化每个对象通过共享相同的内部状态降低了对象的创建和内存占用成本
9 months ago
例如我需要对3个文件获取词频前十的单词对另外3个文件获取词频前二十的单词那么我只需要创建2个词频统计器对象每个对象存储相同的内部状态一个对象
获取前十的单词一个对象获取前二十的单词而不用创建6个对象
'''
9 months ago
from cppy.cp_util import *
9 months ago
#定义享元接口
class WordFrequencyController():
def print_word_freqs(self,number):
pass
#定义具体的享元类
class ConcreteWordFrequencyController(WordFrequencyController):
def __init__(self, controllertype,filepath):
9 months ago
self.word_list = extract_file_words(filepath)
9 months ago
self.word_freq = get_frequencies(self.word_list)
self.word_freq = sort_dict(self.word_freq)
def print_word_freqs(self, number):
for (w, c) in self.word_freq[:number]:
print(w, '-', c)
#定义享元工厂
class WordFrequencyControllerFactory():
def __init__(self):
self.types = {}
def get_WordFrequencyController(self, controller_type,testfilepath):
if controller_type not in self.types:
self.types[controller_type] = ConcreteWordFrequencyController(controller_type,testfilepath)
9 months ago
#创建新的享元对象
9 months ago
return self.types[controller_type]#重复使用已存在的享元对象
def process_command(factory: WordFrequencyControllerFactory, number: str):
controller_type = number
WordFrequencyController = factory.get_WordFrequencyController(controller_type,testfilepath)
WordFrequencyController.print_word_freqs(int(number))
if __name__ == "__main__":
factory = WordFrequencyControllerFactory()
while True:
try:
9 months ago
number = input("请输入需要显示词频前几的单词: ")
9 months ago
process_command(factory, number)
except EOFError:
break