享元模式(Flyweight)

来源:互联网 发布:数据安全 编辑:程序博客网 时间:2024/05/22 03:13


感觉就像是在运用c++中的STL容器map:


using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 享元模式{    abstract class Game   //游戏    {        public abstract void Play();    }    //具体的游戏    class ConcreteGame : Game    {        private string name = "";        public ConcreteGame(string name)        {            this.name = name;        }        public override void Play()        {            Console.WriteLine("运行游戏:" + name);        }    }    class GameFactory   //游戏工厂    {        private Hashtable flyweights = new Hashtable();        //获得游戏分类        public Game GetGameCategory(string key)        {            if (!flyweights.ContainsKey(key))                flyweights.Add(key, new ConcreteGame(key));            return ((Game)flyweights[key]);        }        //获得游戏分类总数        public int GetGameCount()        {            return flyweights.Count;        }    }    class Program    {        static void Main(string[] args)        {            GameFactory f = new GameFactory();            Game zs = f.GetGameCategory("斗地主");            zs.Play();            Game ls = f.GetGameCategory("斗地主");            ls.Play();            Game ww = f.GetGameCategory("斗地主");            ww.Play();            Game zl = f.GetGameCategory("麻将");            zl.Play();            Game sq = f.GetGameCategory("麻将");            sq.Play();            Game zb = f.GetGameCategory("麻将");            zb.Play();            Console.WriteLine("游戏逻辑总数为 {0}", f.GetGameCount());            Console.Read();        }    }}


原创粉丝点击