Singleton模式(Singleton创建类型)c#简单的例子

时间:2022-09-02 08:50:44

单(Singleton创建模式)c#简单的例子

当需要生成一个实例,可单发模式

样品可以在短短的球员中产生,玩家和测试。单线程例子,如以下:

namespace singletonpattern
{
    public partial class SingletonForm : Form
    {
        public SingletonForm()
        {
            InitializeComponent();
        }

        private void btnDisplay_Click(object sender, EventArgs e)
        {
            player player1 = player.GetPlayer;
            player1.jump = "跳一跳";
            player1.move = "走一走";//对player1赋值
            listBox1.Items.Add("------play1.jump,player1.move-------");
            listBox1.Items.AddRange(new string[] { player1.jump, player1.move });

            player player2 = player.GetPlayer;//未对player2赋值,但值与player1同样
            listBox1.Items.Add("------play2.jump,player2.move-------");
            listBox1.Items.AddRange(new string[] { player2.jump, player2.move });

            player1.jump = "跳一跳,跑一跑";
            player1.move = "走一走,看--看";//改动的player1。player2也被改动,说明是同一个类
            listBox1.Items.Add("------play2.jump,player2.move-------");
            listBox1.Items.AddRange(new string[] { player2.jump, player2.move });

            listBox1.Items.Add(object.ReferenceEquals(player1, player2));//显示为true,说明两个为同一个类

        }
    }
    class player
    {
        private player()//单例第一步,设构造函数为私有的。

{ } private static player getplayer; public static player GetPlayer//第二步获取单例 { get { if (getplayer == null)//推断是否实例唯一 { getplayer = new player(); } return getplayer; } } public string jump { get; set; }//单例中的属性 public string move { get; set; } } }

当中
 private static player getplayer;
        public static player GetPlayer//第二步获取单例
        {
            get
            {
                if (getplayer == null)//推断是否实例唯一
                {
                    getplayer = new player();
                }
                return getplayer;
            }

        }
可简化为一句

 

       public static readonly player GetPlayer = new player();//简化单例模式

此文件由朱朱编写,转载请注明出自朱朱家园http://blog.csdn.net/zhgl7688



版权声明:本文博客原创文章。博客,未经同意,不得转载。