zoukankan      html  css  js  c++  java
  • Singleton模式(Singleton创建类型)c#简单的例子

    单(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



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

  • 相关阅读:
    IIT(ISM) Virtual Farewell E Dictator's plan for Valentine's day! 二分
    HDU
    LightOJ
    HDU 4407 Sum 容斥原理
    HDU 4686 Arc of Dream 矩阵快速幂
    uoj418
    Gym101237C The Palindrome Extraction Manacher
    Codeforces 100032 K
    codechef Suffix Palindromes
    Codeforces 932G Palindrome Partition
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4745922.html
Copyright © 2011-2022 走看看