Design Mode: Singleton mode and Design Mode
Singleton mode ensures that a class has only one instance and provides a global access point to access it.
Generally, we can make a global variable to make an object accessible, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance.
The following code uses two button buttons to pop up a small window, but only one small window can be created. You cannot click a button to create a small window. You should click the first button to create a small window, if you click the second button, the system will not be created.
The Code is as follows:
Form1:
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. threading. tasks; using System. windows. forms; namespace Singleton mode dual lock {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button#click (object sender, EventArgs e) {Form2 fm = Form2.GetInstance (); fm. mdiParent = this; fm. show ();} private void button2_Click (object sender, EventArgs e) {Form2 fm = Form2.GetInstance (); fm. mdiParent = this; fm. show () ;}} class Singleton {}}
Form2 (small window ):
Using System; using System. collections. generic; using System. componentModel; using System. data; using System. drawing; using System. linq; using System. text; using System. threading. tasks; using System. windows. forms; namespace Singleton mode dual lock {public partial class Form2: Form {private static Form2 instance; private static readonly object syncRoot = new object (); private Form2 () {InitializeComponent ();} public static Form2 GetInstance () {if (instance = null) {lock (syncRoot) {if (instance = null) {instance = new Form2 () ;}} return instance;} private void Form2_Load (object sender, EventArgs e ){}}}
Running result: