Single-piece mode (Singleton creation type) c # simple example,
Single-piece (Singleton Creation Mode) c # simple example
You can use the single-piece mode to generate an instance.
In this example, you can generate only one player and test the player. An example of a single thread is as follows:
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 = ""; // assign the value to player1 to listBox1.Items. add ("------ play1.jump, player1.move -------"); listBox1.Items. addRange (new string [] {player1.jump, player1.move }); Player player2 = player. getPlayer; // player2 is not assigned a value, but the value is the same as player1 listBox1.Items. add ("------ play2.jump, player2.move -------"); listBox1.Items. addRange (new string [] {player2.jump, player2.move}); player1.jump = "one-hop, one-run"; player1.move = "one-stop, watch-see"; // modified player1, player2 is also modified, indicating the same class listBox1.Items. add ("------ play2.jump, player2.move -------"); listBox1.Items. addRange (new string [] {player2.jump, player2.m Ove}); listBox1.Items. add (object. referenceEquals (player1, player2); // The result is displayed as true, indicating that the two are of the same class.} class player {private player () // the first step of the Singleton, set the constructor to private. {} Private static player getplayer; public static player GetPlayer // The second step obtains the singleton {get {if (getplayer = null) // determine whether the instance is unique {getplayer = new player ();} return getplayer ;}} public string jump {get; set ;} // attribute public string move {get; set ;}} In the singleton ;}}}
Where
Private static player getplayer; public static player GetPlayer // The second step obtains the singleton {get {if (getplayer = null) // determine whether the instance is unique {getplayer = new player () ;}return getplayer ;}}
Can be simplified to one sentence
Public static readonly player GetPlayer = new player (); // simplifies the singleton mode.