Programming of a policy mode code
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;/// <summary>///Summary description of Class1/// </summary> Public InterfaceCalculator//declaring a computed interface { DoubleCal (DoubleADoubleb); } Public classAdd:calculator//The interface implements the addition operation { Public DoubleCal (DoubleADoubleb) {Doubleresult =0; Result= A +b; returnresult; } } Public classSub:calculator//The interface implements the subtraction operation { Public DoubleCal (DoubleADoubleb) {Doubleresult =0; Result= A-b; returnresult; } } Public classMul:calculator//interface to implement multiplication operations { Public DoubleCal (DoubleADoubleb) {Doubleresult =0; Result= A *b; returnresult; } } Public classDiv:calculator//The interface implements the division operation { Public DoubleCal (DoubleADoubleb) {Doubleresult =0; Result= A/b; returnresult; } } Public classEnvironment//define the object that needs to dynamically change the algorithm { PrivateCalculator Calculate; PublicEnvironment (Calculator calculate) { This. Calculate =calculate; } Public DoubleCal (DoubleADoubleB, String m)//returns the result of the operation { return This. Calculate. Cal (A, b); } }
The writing of the binary ASP code and the reference policy mode
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.IO; Public Partial classyunsuan:system.web.ui.page{protected voidPage_Load (Objectsender, EventArgs e) { } protected voidBianji_click (Objectsender, EventArgs e) {Environment Environment=NULL; DoubleA = Convert.todouble (left. Text);//Assigning a value to a related variable Doubleb =convert.todouble (right. Text); stringm =Fuhao. Text; Switch(m) { Case "+": Environment=NewEnvironment (NewADD ());//a reference to a policy pattern Break; Case "-": Environment=NewEnvironment (NewSub ()); Break; Case "*": Environment=NewEnvironment (NewMul ()); Break; Case "/": Environment=NewEnvironment (NewDiv ()); Break; default: Break; } stringAnswer =environment. Cal (A, B, M). ToString (); if(Textbox4.text = =answer. ToString ()) {Response.Write ("Answer Right");//determine if the user is answering correctly and give relevant hints } Else{Response.Write ("answer the wrong"); } ListBox1.Items.Add (left. Text+ Fuhao. Text + right. Text + Label1.Text + answer +"\ n");//The formula is saved to the ListBox control and the correct answer is givenLeft. Text =""; Fuhao. Text=""; Right. Text=""; Textbox4.text=""; } }
The effect of three-interface operation
Code implementation of the calculator software (policy mode +asp.net)