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