201802181721->深入浅出设计模式:c#享元模式

xiaoxiao2021-02-28  50

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _010享元模式 {     /*--------------------------------------------------对象工厂--------------------------------------------------*/     public class FlyWeightFactory     {         public Hashtable container;         private FlyWeight flyWeight;         public FlyWeightFactory()         {             container = new Hashtable();             container.Add("A", new FlyWeightContainer("A"));             container.Add("B", new FlyWeightContainer("B"));             container.Add("C", new FlyWeightContainer("C"));         }         public FlyWeight Get(string key)         {             flyWeight = container[key] as FlyWeight;             if (flyWeight != null)             {                 Console.WriteLine("对象不在对象池中...,{0}", key);                 return new FlyWeightContainer(key);             }             return flyWeight;         }     }     /*--------------------------------------------------对象工厂--------------------------------------------------*/     /*--------------------------------------------------抽象容器以及具体容器--------------------------------------------------*/     public abstract class FlyWeight     {         public abstract void Operation(int innerstate);     }     public class FlyWeightContainer : FlyWeight     {         private string FlyWeightState;         public FlyWeightContainer(string flyweightstate)         {             FlyWeightState = flyweightstate;         }         public override void Operation(int innerstate)         {             Console.WriteLine(string.Format("具体实现类,{0} : {1}", FlyWeightState, innerstate));         }     }     /*--------------------------------------------------抽象容器以及具体容器--------------------------------------------------*/     internal class Program     {         private static void Main(string[] args)         {             int InnerState = 10;             FlyWeightFactory factory = new FlyWeightFactory();             FlyWeight TempFlyWeight = factory.Get("A");             TempFlyWeight.Operation(--InnerState);             TempFlyWeight = factory.Get("A");             TempFlyWeight.Operation(--InnerState);             /*              *              * 享元模式大致可以看作是unity里边的对象池              *              * 在声明的时候就存入需要取出的对象              *              * 在需要用的时候就取,取不到就新建一个              *              *              */             Console.ReadKey();         }     } }
转载请注明原文地址: https://www.6miu.com/read-2624735.html

最新回复(0)