zoukankan      html  css  js  c++  java
  • C# 享元模式(Flyweight)

    理解:有大量相同类型对象需要创造出来时,可以一种类型只保存一个实例,可以改它的外部状态(如位置,名称等)

    代码:

    using System.Collections;
    using System.Windows.Forms;

    namespace DesignMode.Flyweight
    {
        //抽象棋子类
        public abstract class Chessman
        {
            public abstract void Move(int x,int y);
             
        }

        //白棋子
        public class White_Chessman : Chessman
        {
            public override void Move(int x,int y)
            {
                MessageBox.Show("白棋下在:X=" + x + ",Y=" + y);
            }
        }

        //黑棋子
        public class Black_Chessman : Chessman
        {
            public override void Move(int x, int y)
            {
                MessageBox.Show("黑棋下在:X=" + x + ",Y=" + y);
            }
        }


        public class ChessmanFactory
        {
            private Hashtable chessmans = new Hashtable();

            public Chessman GetChessman(string color)
            {
                if (!chessmans.ContainsKey(color))
                {
                    if (color.Equals(""))
                    {
                        chessmans.Add(color, new White_Chessman());
                    }
                    else
                    {
                        chessmans.Add(color, new Black_Chessman());
                    }

                }

                return (Chessman)chessmans[color];
            }
        }} 

     客户端代码:

           

             private void btn_Flyweight_Click(object sender, EventArgs e)

     {
                ChessmanFactory factory = new ChessmanFactory();
                Chessman white1 = factory.GetChessman("");
                white1.Move(510);

                Chessman black1 = factory.GetChessman("");
                black1.Move(612);

                Chessman white2 = factory.GetChessman("");
                white2.Move(714);

                Chessman black2 = factory.GetChessman("");
                black2.Move(1018);
            }

  • 相关阅读:
    b4a专用压缩库(国外免费)
    使用php从pc端下载apk到android手持终端并安装(比如把枪)
    快速搭建电子商务网站以及app
    【转】C#如何创建泛型类T的实例
    【转】C# 之泛型详解
    【转】Windows Server 2016 安装 IIS 服务时提示指定备用源路径
    C# json字符串转为对象
    【转】C#模拟http 发送post或get请求
    【转】Windows IIS注册asp 此操作系统版本不支持此选项 错误解决方法
    Webapi文件上传
  • 原文地址:https://www.cnblogs.com/kavilee/p/2376375.html
Copyright © 2011-2022 走看看