简单工厂模式
实现一个计算机的功能,可以对两个数进行加、减、剩、除
1、创建一个运算类,让具体的运算去继承
public class Operation
{
private double numberA = 0;
private double numberB = 0;
public double NumberA {
get { return numberA; }
set { numberA = value; }
}
public double NumberB {
get { return numberB; }
set { numberB = value; }
}
public virtual double GetResult() {
double result = 0;
return result;
}
}
2、具体的操作类去继承操作类
//加法类 class OperAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } //减法类 class OperSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } //剩法类 class OperMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } //除法类 class OperDiv : Operation { public override double GetResult() { double result = 0; return result = NumberA / NumberB; } }
3、简单工厂类,里面有一个创建运算类的方法
//运算工厂类 public class OperationFactory { //创建具体类的静态方法 public static Operation CreateOperation(string str){ Operation oper = null; switch (str) { case "+": oper = new OperAdd(); break; case "-": oper = new OperSub(); break; case "*": oper = new OperMul(); break; case "/": oper = new OperDiv(); break; } return oper; } }
3、客户端代码
static void Main(string[] args) { // 直接通过简单工厂创建运算类 Operation oper = OperationFactory.CreateOperation("+"); oper.NumberA = 8; oper.NumberB = 10; oper.GetResult(); }