Flyweight vs object pool patterns: When is each useful?

六眼飞鱼酱① 提交于 2019-11-29 05:54:09

问题


As far as I know the object pool is a creational pattern and the flyweight is a structural pattern, but actually I can´t see very much difference between the two. Could someone please explain to me the difference and when each could be useful in an implementation?


回答1:


One difference in that flyweights are commonly immutable instances, while resources acquired from the pool usually are mutable.

So you create flyweights to avoid the cost of repeatedly create multiple instances of objects containing the same state (because they are all the same, you just create only one and reuse it throughout all places in your app), while resources in a pool are particular resources that you want to control individually and possibly have different state, but you don't want to pay the cost of creation and destruction because they are all initialized in the same state.




回答2:


At least two major differences come to mind:

  • An object pool is a container for a set of domain objects while a flyweight usually is a domain object.
  • An object pool usually contains a set of similar objects that can be shared concurrently, such as database connections, while there is usually a set of different flyweight objects, each representing a different state.



回答3:


This site describes both patterns with specific examples. It does a pretty goo job clarifying the difference and supports Gabriel's response above. http://www.oodesign.com/



来源:https://stackoverflow.com/questions/9322141/flyweight-vs-object-pool-patterns-when-is-each-useful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!