The Flyweight design pattern uses sharing to support large numbers of fine-gained objects efficiently.
享元模式用共享有效支持大量细粒度的对象。
UML Class Diagram
Flyweight: The flyweight interface enables sharing but it does not enforce it. The concrete objects which implement this interface either be shared or unshared. This is going to be an interface that defines the members of the flyweight objects.
ConcreteFlyweight: The ConcreteFlyweight class which implements the Flyweight interface, adds storage for the instrinsic state. it must be shareable and any state we are going to be store in this object should be in an instrinsic state.
FlyweightFactory: The FlyweightFactory has the GetFlyweight method and you have to pass the key to this method.It will check based on the key, whether the flyweight object is there in the cache or not. if it is there it will return that existing flyweight object, And if it is not there, then it will create a new flyweight object and add that object to the cache and return that flyweight object.
Structure code in C#
public class FlyweightFactory { //The following dictionary is going to act as out Cache memory. private Dictionary<string, IFlyweight> flyweights = new Dictionary<string, IFlyweight>(); public FlyweightFactory() { flyweights.Add("X", new ConcreteFlyweight()); flyweights.Add("Y", new ConcreteFlyweight()); flyweights.Add("Z", new ConcreteFlyweight()); } public IFlyweight GetFlyweight(string key) { return ((IFlyweight)flyweights[key]); } }FlyweightFactory
/// <summary> /// Flyweight interace /// This is an interface that defines the members of the flyweight objects /// </summary> public interface IFlyweight { void Operation(int extrinsicState); } public class ConcreteFlyweight : IFlyweight { public void Operation(int extrinsicState) { Console.WriteLine($"ConcreteFlyweight: {extrinsicState}."); } } public class UnsharedConcreteFlyweight : IFlyweight { public void Operation(int extrinsicState) { Console.WriteLine($"UnsharedConcreteFlyweight; {extrinsicState}."); } }Flyweight
When to use Flyweight Design Pattern in Real-Time application?
- Many similar objects are used and the storage coast is high.
- The majority of each object's state data can be made extrinsic.
- A few shared objects would easily replace many unshared objects.
- The identity of each object does not matter