单件(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();//简化单例模式