享元模式

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
posted @   云霄宇霁  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示