Flyweight 设计模式是否适用于降低实例化成本?

Is the Flyweight design pattern applicable for reducing instantiation costs?

Design patterns 书中给出了享元设计模式的以下适用性(大胆强调我的):

Applicabilty

The Flyweight pattern’s effectiveness depends heavily on how and where it’s used. Apply the Flyweight pattern when all of the following are true:

  • An application uses a large number of objects.
  • Storage costs are high because of the sheer quantity of objects.
  • Most object state can be made extrinsic.
  • Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.
  • The application doesn’t depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

而不是存储成本(space 资源),实例化成本(时间资源)是否会产生有效的应用程序还有吗?

享元设计模式只是缓存的一种特殊应用。在无法缓存整个对象的场景下,因为对象的某些状态是唯一的,Flyweight 提醒我们,我们可能仍然缓存对象的部分,如果我们分离出一部分不是唯一的,可以共享。

由于 Flyweight 只不过是部分缓存,它通常提供与缓存相同的好处,包括减少时间和 space 复杂性。因此,您的问题的答案是肯定的,实例化成本(时间资源)使得享元模式的有效应用成为可能。当然,这是假设您不能只缓存整个对象,这比缓存部分对象要简单得多。