'''
装饰器模式 (Decorator Pattern)

适用场景：动态为词频统计添加功能，如过滤停用词、忽略标点、或添加词性标注。
如何应用：
定义核心 WordCounter 接口，负责基本词频统计。

使用装饰器类动态添加功能，如 StopWordFilterDecorator 过滤停用词。

优点：功能扩展不修改核心逻辑，符合开闭原则。

知识点：
如何动态扩展功能，保持核心代码不变。
体会组合优于继承的原则。

'''

from abc import ABC, abstractmethod
from typing import List, Dict
from collections import Counter

class WordCounter(ABC):
    @abstractmethod
    def count_words(self, texts: List[str]) -> Dict[str, int]:
        pass

class BasicWordCounter(WordCounter):
    def count_words(self, texts: List[str]) -> Dict[str, int]:
        import jieba
        word_counts = Counter()
        for text in texts:
            words = jieba.cut(text)
            word_counts.update([word for word in words if word.strip()])
        return dict(word_counts)

class WordCounterDecorator(WordCounter, ABC):
    def __init__(self, counter: WordCounter):
        self.counter = counter

class StopWordFilterDecorator(WordCounterDecorator):
    def __init__(self, counter: WordCounter, stop_words: List[str]):
        super().__init__(counter)
        self.stop_words = stop_words

    def count_words(self, texts: List[str]) -> Dict[str, int]:
        word_counts = self.counter.count_words(texts)
        return {word: count for word, count in word_counts.items() if word not in self.stop_words}

# 使用
counter = StopWordFilterDecorator(BasicWordCounter(), stop_words=["的", "了", "是"])
word_counts = counter.count_words(["这是一段测试文本。"])
print(word_counts)