文本是《设计模式(共12篇)》专题的第 9 篇。阅读本文前,建议先阅读前面的文章:
享元模式详解
1️⃣ 概念
定义: 提供了减少对象数量从而改善应用所需的对象结构的方式;运用共享技术有效地支持大量细粒度的对象;
类型: 结构性
2️⃣ 适用场景
- 常常应用于系统底层的开发,以便解决系统的性能问题;
 - 系统有大量的相似对象,需要缓冲池的场景;
 
3️⃣ 优点
- 减少对象的创建,降低内存中对象的数量,较低系统的内存,提升效率;
 - 减少内存之外的其他资源占用;
 
4️⃣ 缺点
- 关注内外部状态,关注线程安全问题;
 - 使系统程序的逻辑复杂化;
 
5️⃣ 享元模式 Python实现
① 创建 Employee 抽象基类
from abc import ABC, abstractmethod
class Employee(ABC):
    @abstractmethod
    def report(self):
        pass
② 创建 Manager 类继承抽象基类
class Manager(Employee):
    def __init__(self, department):
        self.title = "部门经理"
        self.department = department
        self.report_content = None
    def report(self):
        print(self.report_content)
    def set_report_content(self, report_content):
        self.report_content = report_content
③ 创建 EmployeeFactory 工厂类
class EmployeeFactory:
    EMPLOYEE_MAP = {}
    @staticmethod
    def get_manager(department):
        manager = EmployeeFactory.EMPLOYEE_MAP.get(department)
        if manager is None:
            manager = Manager(department)
            print(f"创建部门经理:{department}", end="")
            report_content = f"{department}部门汇报:此次报告的主要内容是......"
            manager.set_report_content(report_content)
            print(f" 创建报告:{report_content}")
            EmployeeFactory.EMPLOYEE_MAP[department] = manager
        return manager
④ 编写测试函数
import random
def test_flyweight_pattern():
    departments = ["RD", "QA", "PM", "BD"]
    for i in range(10):
        department = random.choice(departments)
        manager = EmployeeFactory.get_manager(department)
        manager.report()
if __name__ == "__main__":
    test_flyweight_pattern()
6️⃣ 享元模式的应用
Python 中的字符串常量池:
Python 中的字符串缓存机制类似于享元模式的应用。对于小整数和短字符串,Python 会自动复用对象实例。
# 字符串享元示例
a = "hello"
b = "hello"
print(a is b)  # True,说明是同一个对象
# 小整数享元示例
x = 100
y = 100
print(x is y)  # True,Python 缓存了 -5 到 256 的整数
您已阅读完《设计模式(共12篇)》专题的第 9 篇。请继续阅读该专题下面的文章:
