Design Patterns in C#: Flyweight
The Flyweight pattern provides for sharing an object between clients, creating a responsibility for the shared object that normal objects need not consider. An ordinary object doesn’t have to worry much about shared responsibility. Most often, only one client will hold a reference to an object at any one time. When the object’s state changes, it’s because the client changed it, and the object does not have any responsibility to inform any other clients. Sometimes, though, you will want to arrange for multiple clients to share access to an object.
One incentive for sharing an object among multiple clients occurs when you must manage thousands or tens of thousands of small objects, such as the characters in an online version of a book. In such a case, you may have a performance incentive to share these fine-grained objects among many clients. A book needs only one A object, although it needs some way to model when different As appear.
In any application that has a large number of small objects, you may need to provide a way for clients to safely share the common elements of these objects. The intent of the Flyweight pattern is to use sharing to support large numbers of fine-grained objects efficiently.
Immutability
The Flyweight pattern lets multiple clients share access to a limited number of objects—the flyweights. For this to work, you have to consider that when a client changes the state of an object, the state changes for every client that has access to the object. When multiple clients share access to an object, the easiest and most common way to keep clients from affecting each other is to restrict clients from introducing any state changes in the shared object. You can achieve this by making an object immutable (that is, unchangeable) so that once created, the object cannot change. The most common immutable objects in C# are instances of the String class. Once you create a string, neither you nor any client with access to the string can change its characters.
Challenge 13.1
Provide a justification of why the creators of C# made String objects immutable, or argue that this was an unwise restriction.
A solution appears on page 378.
When you have large numbers of similar objects, you may want to arrange for shared access to these objects, but they may not be immutable. In this case, a preliminary step in applying the Flyweight pattern is to extract the immutable part of an object so that this part can be shared.