• 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);
            }

  • 相关阅读:
    Java 设计模式——状态模式
    Java 设计模式——外观模式
    Java高级之虚拟机加载机制
    17.1.1.6 Creating a Data Snapshot Using Raw Data Files 创建一个数据快照使用 Raw Data Files
    17.1.1.5 Creating a Data Snapshot Using mysqldump
    17.1.1.4 Obtaining the Replication Master Binary Log Coordinates 得到复制master binary log 位置:
    17.1.1.3 Creating a User for Replication 创建一个用于用于复制:
    17.1.1.2 Setting the Replication Slave Configuration
    17.1.1.1 Setting the Replication Master Configuration 设置复制的master 配置:
    17.1.1 How to Set Up Replication 设置复制:
  • 原文地址:https://www.cnblogs.com/kavilee/p/2376375.html
Copyright © 2020-2023  润新知