This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding Flyweight pattern

 
Paritosh H Chandorkar
Ranch Hand
Posts: 90
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

I have yet not understood the logic of the FlyWeight pattern implementation.
Can you please explain me in brief with suitable example?
Please do share the useful links as well.

Thanks and regards,
Paritosh Chandorkar
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paritosh H Chandorkar
Ranch Hand
Posts: 90
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Jelle,for the reply.I got a hang of it now.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic