享元模式
字数: 0

基本概念

notion image
Flyweight Pattern: Use sharing to support large numbers of fine-grained objects efficiently.
(A flyweight is a shared object that can be used in multiple contexts simultaneously.)
它摒弃了在每个对象中保存所有数据的方式, 通过共享多个对象所共有的相同状态, 能在有限的内存容量中载入更多对象。

相关联系

  • 如果能将对象的所有共享状态简化为一个享元对象, 那么享元模式和
    单例模式
    类似。 但这两个模式有两个根本性的不同:
      1. 只会有一个单例实体, 但是享元类可以有多个实体, 各实体的内在状态也可以不同。
      1. 单例对象可以是可变的。 享元对象是不可变的。
        1. 享元与不可变性 (Immuteable)
          享元与不可变性 (Immuteable)
          享元类的状态只能由构造函数的参数进行一次性初始化, 它不能对其他对象公开其设置器或公有成员变量。
  • 可以使用享元模式实现
    组合模式
    树的共享叶节点以节省内存。
  • 享元模式展示如何生成大量的小型对象,
    观察者模式
    展示如何用一个对象代表整个子系统。

实现代码

享元

享元工厂

测试类

Q & A

What are the advantages of using flyweight design patterns?
  • You can decrease the total number of “complete but similar objects” in the system, thus reducing memory consumptions
  • You can provide a centralized mechanism to control the states of many “virtual” objects.
What are the challenges associated with using flyweight design patterns?
To create flyweights, you extract a common template class from the existing objects. This additional layer of programming can be tricky and sometimes hard to debug and maintain.

具体应用

java.lang.Xxxxx#valueOf(xxx) 

java.lang.Integer#valueOf(int) (以及 Boolean、 Byte、 Character、 Short、 Long 和 Big­Decimal
notion image
2023 - 2026