Simple factory Mode c #,
Simple factory Mode c # simple example
Namespace simplefactory
{
Public partial class Form1: Form
{
Private void button#click (object sender, EventArgs e) // user level
{
Operation operation = OperationFactory. createOperate (this. cbbOperation. SelectedIndex); // connect to the simple factory to obtain the algorithm
Operation. NumberA = Convert.ToDouble(this.txt NumberOne. Text); // assign values to the algorithms obtained from a simple factory.
Operation. NumberB = Convert.ToDouble(this.txt NumberTwo. Text );
This.txt Result. Text = operation. getResult (). ToString (); // obtain the algorithm Result
}
}
Class OperationFactory // simple factory level
{
Public static Operation createOperate (int operate) // two types of factory division addition and subtraction
{
Operation operator = null;
Switch (operate)
{
Case 0:
{
Operator = new OperationAdd (); // Addition
Break;
}
Case 1:
{
Operator = new OperationSub (); // Subtraction
Break;
}
}
Return response;
}
}
Public abstract class Operation // The line abstraction for addition and subtraction algorithms to facilitate uniform assignment of NumberA and NumberB and calculation result getResult ()
{
Public double NumberA {get; set ;}
Public double NumberB {get; set ;}
Public abstract double getResult ();
}
Class OperationAdd: Operation // Addition Algorithm inherits the abstract algorithm
{
Public override double getResult ()
{
Return NumberA + NumberB;
}
}
Class OperationSub: Operation // The subtraction algorithm inherits the abstract algorithm.
{
Public override double getResult ()
{
Return NumberA-NumberB;
}
}
}