Flyweight vs object pool patterns: When is each useful?
Asked Answered
S

3

24

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?

Scholarship answered 17/2, 2012 at 2:37 Comment(0)
F
35

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.

Floccule answered 17/2, 2012 at 2:56 Comment(2)
The best answer! I think, that Flyweight is usually used to minimize memory volume, because it contains only unique items. Object pool allows to improve performance but leads to high memory consumption.Cott
To some extend, I think flyweight pattern also caches something. If the single immutable flyweight occupies too much memory, it's difficult to say the memory saving. You can say it's better than you create these immutable objects once and once again.Liberate
B
5

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.
Bolection answered 17/2, 2012 at 3:7 Comment(0)
T
1

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/

Transarctic answered 17/2, 2012 at 3:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.