05 Dec 2023
Advanced
The Flyweight design pattern is a structural pattern that aims to minimize memory usage or computational expenses by sharing as much as possible with related objects. In C#, the Flyweight pattern typically involves the following main components:
-
Flyweight Interface:
- Declares an interface through which flyweights can receive and act on extrinsic (state-dependent) information.
public interface IFlyweight { void Operation(int extrinsicState); } -
Concrete Flyweight:
- Implements the Flyweight interface.
- Stores intrinsic (state-independent) information that can be shared across multiple objects.
public class ConcreteFlyweight : IFlyweight { private string intrinsicState; public ConcreteFlyweight(string intrinsicState) { this.intrinsicState = intrinsicState; } public void Operation(int extrinsicState) { Console.WriteLine($"ConcreteFlyweight: Intrinsic state: {intrinsicState}, Extrinsic state: {extrinsicState}"); } } -
Flyweight Factory:
- Manages a pool of flyweight objects.
- Ensures that flyweights are shared and reused when requested.
public class FlyweightFactory { private Dictionary<string, IFlyweight> flyweights = new Dictionary<string, IFlyweight>(); public IFlyweight GetFlyweight(string key) { if (!flyweights.ContainsKey(key)) { flyweights[key] = new ConcreteFlyweight(key); } return flyweights[key]; } } -
Client:
- Maintains extrinsic state (state that varies between objects).
- Collaborates with flyweights by acquiring them from the flyweight factory.
class Client { static void Main() { FlyweightFactory factory = new FlyweightFactory(); IFlyweight flyweight1 = factory.GetFlyweight("A"); flyweight1.Operation(1); IFlyweight flyweight2 = factory.GetFlyweight("B"); flyweight2.Operation(2); IFlyweight flyweight3 = factory.GetFlyweight("A"); flyweight3.Operation(3); // The intrinsic state is shared between flyweight1 and flyweight3 // Output: // ConcreteFlyweight: Intrinsic state: A, Extrinsic state: 1 // ConcreteFlyweight: Intrinsic state: B, Extrinsic state: 2 // ConcreteFlyweight: Intrinsic state: A, Extrinsic state: 3 } }
In this example:
IFlyweightis the interface that declares the operation method that flyweights must implement.ConcreteFlyweightis a concrete implementation of the flyweight interface and holds intrinsic state.FlyweightFactorymanages a pool of flyweight objects and ensures that they are shared and reused.- The
Clientmaintains extrinsic state and collaborates with flyweights by acquiring them from the flyweight factory.
The Flyweight pattern is beneficial when you have a large number of similar objects and want to reduce memory usage or computational expenses by sharing as much as possible. The pattern separates intrinsic and extrinsic state, allowing the intrinsic state to be shared among multiple objects.
software-design-patterns
flyweight-design-pattern