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?
Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.
Advantage of Object Pool design patternIt is most effective in a situation where the rate of initializing a class instance is high. It manages the connections and provides a way to reuse and share them. It can also provide the limit for the maximum number of objects that can be created.
Advantages of Flyweight Design Pattern The Flyweight Pattern contributes to improving the performance of the application by reducing the number of objects. The Flyweight Pattern reduces the memory footprint and saving RAM as the common properties are shared between objects using Intrinsic properties.
The flyweight pattern is best suited to scenarios where the number of objects that the factory will need to create and remember is finite and compatible with the memory constraints on the application.
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.
At least two major differences come to mind:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With