享元模式
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]); } }

/// <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}."); } }
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)