自学内容网 自学内容网

C#设计模式(12)——享元模式(Flyweight Pattern)

前言

享元模式通过共享对象来减少内存使用和提高性能。

代码

public abstract class Flyweight
{
    public abstract void Control();
}

public class ComputerFlyweight : Flyweight
{
    private string _operator;

    public ComputerFlyweight(string name)
    {
        _operator = name;
    }
    public override void Control()
    {
        Console.WriteLine($"current computer operator is :{_operator}");
    }
}

public class FlyweightFactory
{
    private Dictionary<string, Flyweight> flyweights = new Dictionary<string, Flyweight>();
    public Flyweight GetFlyweight(string key)
    {
        if (flyweights.ContainsKey(key))
        {
            return flyweights[key];
        }
        else
        {
            Flyweight flyweight = new ComputerFlyweight(key);
            flyweights.Add(key,flyweight);
            return flyweight;
        }
    }
}

 /*
  * 结构型模式:Structural Pattern
  * 享元模式:Flyweight Pattern
  */
 internal class Program
 {
     static void Main(string[] args)
     {
         FlyweightFactory factory = new FlyweightFactory();
         Flyweight  userA = factory.GetFlyweight("UserA");
         userA.Control();
         Flyweight userB = factory.GetFlyweight("UserB");
         userB.Control();
         Flyweight userC = factory.GetFlyweight("UserA");
         userC.Control();
         Console.ReadLine();
     }
 }

运行结果

在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_43626218/article/details/143810202

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!