Home  /  Questions  /  Question



50   50
Feb 17, 2011


Flyweight Pattern: why use interface/concrete class organization?

What I don't understand is why you would want to make (for example) 26 specific subclasses of Character when you could just pass the information that identifies each type of character to a constructor for the Character class.  You already have a large switch statement that creates the proper subclass of Character depending on the input; it would be just as easy to have it call the Character constructor with the proper set of values instead.

From what I can tell, the rest of the flyweight architecture - storing objects and reusing them - would happen exactly the same way.

So what am I missing? 



1,364   100.0
Mar 09, 2011
I guess the example in the site is just to demonstrate the use of flyweight pattern wherein we have large no. of small flyweight objects. In this case 'A', 'B', 'C' etc....
But yeah, this may not be the most appropriate example.

The real example of flyweight in .NET can be found in the string class.  See the Intern(str) method of the string.  

http://msdn.microsoft.com/en-us/library/system.string.intern.aspx

The Intern() method uses the intern pool to search for a string equal to the value of str.  If such a string exists, its reference in the intern pool is returned.  If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.

So for eg. you have this snippet..

string s1 = "dummy";
string s2 = "dummy";

Console.WriteLine (ReferenceEquals(s1, s2));   // returns true as it points to the same reference

Using intern this can be done like this...

string s1 = "dummy";
string s2 = Console.ReadLine();
string s3 =  string.Intern(Console.ReadLine());


Console.WriteLine (ReferenceEquals(s1, s2));   // returns false
Console.WriteLine (ReferenceEquals(s1, s3));   // returns true

String.Intern(..) is the FlyWeight Factory object.....

Hope this helps...



Jul 12, 2012
While Rajesh's answer is good, I would like to add the following. I heard someone say people use variables as if it is their Grand Father's property. The idea behind sharing variables is to conserve memory as in the string interning example. However, we do need to treat and represent each character as a separate entitiy. That amounts to very little when seen in the context of a huge document. By sharing those characters we are conserving memory.

    Take an analogy with control derived from CWnd in MFC. Although, all controls are derived from CWnd, we still need to have different classes for CButton, CCheckBox and so on to represent the varied nature of each one. Likewise, each character should be treated separately. Even, in the CWnd derived objects - taking a lesson from the Flyweight patterns - one should try to optimize and share the variables as much as possible.

Hope it helps.

N. Murali Mohan