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
Murali Narayanabhatla, Jul 12, 2012
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.
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...
Rajesh Pillai, Mar 09, 2011