One: Design mode
Concept:
Propose specific solutions for specific issues
II: Simple Factory
eg
Using polymorphic and simple factory design patterns to achieve the calculator, the effect:
//Parent Class Public Abstract classOperation { Public DoubleNumbera {Get;Set; } Public DoubleNumberb {Get;Set; } Public Abstract DoubleGetResult ();} //sub-class addition Public classoperationadd:operation { Public Override DoubleGetResult () {Doubleresult = Numbera +Numberb; returnresult; }} //sub-class subtraction Public classoperationjian:operation { Public Override DoubleGetResult () {Doubleresult = Numbera-Numberb; returnresult; } } //sub-class multiplication Public classoperationcheng:operation { Public Override DoubleGetResult () {Doubleresult = Numbera *Numberb; returnresult; } } //sub-class division Public classoperationchu:operation { Public Override DoubleGetResult () {if(Numberb = =0) { Throw NewException ("the divisor cannot be 0! "); } Doubleresult = Numbera/Numberb; returnresult; } }
Get two operands in the Calculate button, as well as operators, methods of calculation
//get two operand (x ) intNUM1 =Convert.ToInt32 (Txtlist1.text); intnum2 =Convert.ToInt32 (Txtlist2.text); //Get operator stringOper =Cbolist.text; Operation Calc=operationfactory.createinstance (OPER); Calc. Numbera=NUM1; Calc. Numberb=num2; //calculation Method intresult =0; Try{result=Convert.ToInt32 (Calc. GetResult ()); } Catch(Exception ex) {MessageBox.Show (ex). Message); Throw; } Label1. Text= result. ToString ();
Factory class: (CORE)
Three: Single case mode
Singleton mode requires that a class can have only one object
Four steps:
①: Defines a static variable with the same type as the current class name
②: Change construction to private
③: Defines a static method that assigns a value to a static variable, instantiates the object, and returns an instance reference
④: Empty the static variable
Public Partial classForm1:form {//defines a static variable with the same type as the current class name Public StaticForm1 frm; //change construction to private PrivateForm1 () {InitializeComponent (); } //define a static method to assign a value to a static variable Public StaticForm1 getinstance () {if(frm = =NULL) {frm=NewForm1 (); } returnfrm; } //empty a static variable Private voidForm1_formclosing (Objectsender, FormClosingEventArgs e) {frm=NULL; }
Simple factory and single case design mode