C # The first Singleton mode,
When we use QQ, we will find that he can start multiple QQ, but sometimes, we don't want to do this, at this time we need to use the singleton mode. 1. convert the Form2 constructor to private
Using System. Windows. Forms; namespace Singleton mode {public partial class Form2: Form {private Form2 () {InitializeComponent ();}}}
2. Provide a static method to return an object
Using System. windows. forms; namespace Singleton mode {public partial class Form2: Form {private Form2 () {InitializeComponent ();} public static Form2 GetSingle () {Form2 form = new Form2 (); return form ;}}}
3. Call in Form1
Using System; using System. windows. forms; namespace Singleton mode {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {Form2 form = Form2.GetSingle (); // new Form2 (); form. show ();}}}
4. Create a singleton in Form2
Using System. windows. forms; namespace Singleton mode {public partial class Form2: Form {// globally unique Singleton public static Form2 FrmSingle = null; // This is a static field, the initial value is set to null private Form2 () {InitializeComponent ();} public static Form2 GetSingle () {if (FrmSingle = null) // make a judgment, if FrmSingle is null, {FrmSingle = new Form2 () is created; // after this object is created, Form2 is not given, and FrmSingle} return FrmSingle; // return FrmSingle }}}
After completing the above steps, run Form1, regardless of the number of creation buttons, it is only the object created.