设计模式-简单工厂模式
一个简单的计算器
1.首先写一个运算类Operation类
java
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.加减乘除类
java
class OperationAdd : Operation //加法类,继承运算类
{
public override double GetResult(){
double result = 0;
result = NumberA + NumberB;
return result;
}
}
class OperationSub : Operation //减法类,继承运算类
{
public override double GetResult(){
double result = 0;
result = NumberA - NumberB;
return result;
}
}
class OperationMul : Operation //乘法类,继承运算类
{
public override double GetResult(){
double result = 0;
result = NumberA * NumberB;
return result;
}
}
class OperationDiv : Operation //除法类,继承运算类
{
public override double GetResult(){
double result = 0;
if(NumberB == 0)
throw new Exception("除数不能为0。");
result = NumberA / NumberB;
return result;
}
}
3.简单工厂模式
java
public class OperationFactory
{
public static Operation createOperate(string operate){
Operation oper = null;
switch(operate){
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
}
}
客户端调用
java
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
简单工厂模式的好处
1.之后要增加运算,只需要增加OperationXXX即可
2.之后要改某个运算,只需要修改OperationXXX即可