实现简单计算器
简单工厂模式
类图:
代码:
//运算类
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;
}
}
//加法运算
class OperationAdd:Operation
{
public override double GetResult() {
double result = 0;
result = NumberA + NumberB;
return result;
}
}
//减法、乘法。。类似
//运算工厂类
public class OperationFactory
{
public static Operation createOperate(string operate) {
Operation oper = null;
switch (operate) {
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
default:
break;
}
return oper;
}
}
//客户端代码
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
工厂方法模式
类图:
代码:
//运算类
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;
}
}
//加法运算
class OperationAdd:Operation
{
public override double GetResult() {
double result = 0;
result = NumberA + NumberB;
return result;
}
}
//工厂接口
interface IFactory
{
Operation CreateOperation();
}
//加法运算工厂
class AddFactory : IFactory
{
public Operation CreateOperation() {
return new OperationAdd();
}
}
//减法、乘法、除法类似
//客户端代码
IFactory operFactory = new AddFactory();
Operation oper = operFactory.CreateOperation();
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
两种模式对比
工厂方法模式的定义:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类
简单工程模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖
工厂方法克服了简单工厂违背开放-封闭原则的缺点,又保持了封装对象创建过程的优点
开放-封闭原则 是说软件实体(类、模块、函数等等)应该可以扩展,但是不可修改
参考:
《大话设计模式》-----程杰