I. Create a form
Two. Create a class operator there are two operands and one method
Public abstract class Operator {public abstract int Calc (); Count public int Numleft {get; set;} public int Numright {get; set;} }
Three. Create an Add Class
public class Add:operator {public override int Calc () { return this. Numleft + this. numright; } }
Four. Create a sub Class
Public class Sub:operator {public override int Calc () { return this. Numleft-this. numright; } }
Five. Create a Mul class
Public class Mul:operator {public override int Calc () { return this. Numleft * this. numright; } }
Six. Create a DIV class
Public class Div:operator {public override int Calc () { int result = 0; if (Numleft = = 0) { throw new Exception ("divisor cannot be 0"); } else { result=this. Numleft/this. numright; } return result; } }
Seven. Create a factory-like class
Public class Factory { //static return value type parameter public static Operator Cu (String Type) { Operator Oper=null; Switch (Type) {case "+": oper=new Add (); break; Case "-": oper=new Sub (); break; Case "*": oper=new Mul (); break; Case "/": oper=new Div (); break;} return oper; } }
Eight. In the results button of the main form, add
private void Btok_click (object sender, EventArgs e) { int num1=convert.toint32 ( txtlfet.text); String oper = cb. Text; int num2 = Convert.ToInt32 (txtright.text); 04. Call the factory's static method, pass in the type, get the return value Operator part = FACTORY.CU (oper); Part. Numleft = NUM1; Part. Numright = num2; int result = 0; 05. Call the Calc () that corresponds to the parent class variable to complete the calculation, and receive the return value of try { result = part. Calc (); } catch (Exception ex) { MessageBox.Show (ex. Message); } 06. Display the Label1 in the label . Text = result. ToString (); }
Multi-State computer program