Tell me why I studied the singleton pattern:
In the MDI WinForm program, you need each subform can only open once (at the same time only one child form instance), before the Internet to see a good variety of solutions, a variety of attempts to solve the problems I encountered, I believe many people with me, I can now tell you, simple interest mode can be solved perfectly.
Summary of the Singleton pattern:
- Target: Only one instance of a class exists
- Instances of the class are created by themselves.
- Because the class instance can have only one, the constructor for the class must be private
- A logical unit must be inside a class to return to an external class instance (object)
The following is the implementation process:
My MDI subroutine subform (User management--usermgrform)
Private StaticUsermgrform Usrform;//child Form Instance Private Static ReadOnlyObject Asyncroot =NewObject ();//read-only object objects//constructor Function PrivateUsermgrform () {InitializeComponent (); }//The subform creates an instance of the method (must be static, because the instance method is not allowed to be invoked with the class instance, which is meaningless) Public Staticusermgrform getinstance () {if(Usrform = =NULL) { Lock(Asyncroot)//This is a double lock used in multi-threaded{//determine if the subform instance is null if(Usrform = =NULL) {Usrform=NewUsermgrform (); } } } returnUsrform; }//Modify the code in the subform UserMgrForm.Designer.cs file to protected Override voidDispose (BOOLdisposing) { if(Disposing && (Components! =NULL) ) {components. Dispose (); }//base. Dispose (disposing); //the original Code Base. Hide (); }//How to implement open subforms in the main form://User Management Private voidMiempmgr_click (Objectsender, EventArgs e) {SysMenu.UserMgrForm.GetInstance (). MdiParent= This; Setui.setformtitle (SysMenu.UserMgrForm.GetInstance (),"User Management");//Form TitleSetui.setmdichildsize (SysMenu.UserMgrForm.GetInstance ());//set the initial size of the subformSetui.setmdiformstate (SysMenu.UserMgrForm.GetInstance ());//Set the subform stateSysMenu.UserMgrForm.GetInstance (). Show ();//Show Subform}
There are several ways to do the singleton pattern, and here's a few.
. NET design patterns for single-instance mode