20

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?

iluwatar
  • 1,778
  • 1
  • 12
  • 22
  • related/duplicate question: http://stackoverflow.com/questions/9322141/flyweight-vs-object-pool-patterns-when-is-each-useful – Fuhrmanator May 25 '15 at 12:16

1 Answers1

30

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.

felix-b
  • 8,178
  • 1
  • 26
  • 36
  • the best explanation I found so far :3 – Mike Herasimov Sep 25 '16 at 12:38
  • Nice explanation. There're couple of examples of Flyweight pattern I've encountered which save extrinsic/changing state in the flyweight objects. Since the point is reducing the memory footprint by reusing objects, I think it's fine to do it that way as well as long as you think you can manage it. I think the difference stays in the understanding of the object being singleton or not. Once you get this, thread-safety and other management related concerns will eventually strike you. – stdout Mar 20 '17 at 13:25
  • Flyweight object is not a singleton. Intrinsic States: Things that are constant and stored in memory Extrinsic States: Things that are not constant and not stored in memory, calculated on the fly. – Dipon Roy Feb 19 '18 at 06:40
  • Excellent answer just one edit : A Flyweight class can have multiple instances in the FlyweightFactory but only when their objects have different intrinsic states. https://refactoring.guru/design-patterns/flyweight#relations – Number945 Aug 11 '21 at 06:10