享元模式

享元模式:让一个对象共享。

场景:String池。

UML图:

示例代码:

    public abstract class Flyweight
    {
        public abstract void Operation();
    }
    public class ConcreteFlyweight:Flyweight
    {
        public override void Operation()
        {
            Console.WriteLine("Run");
        }
    }
    public class FlywightFactory
    {
        Dictionary<string, ConcreteFlyweight>  dictionary = new Dictionary<string, ConcreteFlyweight>();

        public ConcreteFlyweight GetFlyweight(string key)
        {
            if (dictionary.Keys.Contains(key))
            {
                return dictionary[key];
            }
            var fly = new ConcreteFlyweight();
            dictionary.Add(key, fly);
            return fly;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            FlywightFactory factory = new FlywightFactory();
            var fac = factory.GetFlyweight("chenyishi");
            fac = factory.GetFlyweight("chenyishi");
        }
    }
原文地址:https://www.cnblogs.com/chenyishi/p/9121240.html