享元模式(Flyweight)


感觉就像是在运用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();
        }

    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值