The Flyweight pattern is basically all about resource management, more specifically about supporting large numbers of objects efficiently by encapsulating state in an immutable object (the flyweight) and sharing that object among as many similar objects as possible. One example of a flyweight implementation is actually a well-known mechanism provided by the core Java API: java.lang.String.intern(). XML parsers, for instance, can use the String.intern() mechanism to efficiently share XML tag names (among other things) when processing XML data. Building a complete DOM tree in-memory is already notoriously expensive when it comes to memory consumption. Imagine how much more expensive it would be if the XML parser would have to allocate heap space for a new String object for each and every tag it encouters, regardless of whether or not it had already processed tags with an identical name. A String is immutable by design and the String.intern() method offers a convenient way to add a new value to the constant pool at runtime, so an XML parser can make use of this to keep the number of String objects related to tag names in check. This is the essence of the Flyweight pattern, which in this example is facilited by an object pool. To reiterate, a flyweight object is an immutable object that encapsulates state that can be shared among many other objects - immutability is key because state must be shared safely.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Paritosh H Chandorkar
Joined: Nov 11, 2012
Thanks a lot Jelle,for the reply.I got a hang of it now.