Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Flyweight and Object Pool patterns?

It seems to me that Flyweight and Object Pool patterns are very similar. Both have pools of objects leased to clients. What are the differences?

like image 539
iluwatar Avatar asked May 24 '15 10:05

iluwatar


People also ask

What is object pool design pattern?

The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object.

What is the advantage of object pool design pattern?

Advantage of Object Pool design pattern It 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.

What is the meaning of Flyweight pattern?

In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known GoF design patterns.

What type of design pattern is flyweight?

Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.


1 Answers

They differ in the way they are used.

Pooled objects can simultaneously be used by a single "client" only. For that, a pooled object must be checked out from the pool, then it can be used by a client, and then the client must return the object back to the pool. Multiple instances of identical objects may exist, up to the maximal capacity of the pool.

In contrast, a Flyweight object is singleton, and it can be used simultaneously by multiple clients.

As for concurrent access, pooled objects can be mutable and they usually don't need to be thread safe, as typically, only one thread is going to use a specific instance at the same time. Flyweight must either be immutable (the best option), or implement thread safety. (Frankly, I'm not sure if a mutable Flyweight is still Flyweight :))

As for performance and scalability, pools can become bottlenecks, if all the pooled objects are in use and more clients need them, threads will become blocked waiting for available object from the pool. This is not the case with Flyweight.

like image 76
felix-b Avatar answered Sep 30 '22 00:09

felix-b