《大话设计模式》读书笔记1 简单工厂模式
简单工厂模式(Simple Factory Pattern)属于类的创新型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern),是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
简单工厂模式结构图:
简单工厂模式实现代码:
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;
}
}
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;
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;
case "*"
oper=new OperationMul();
break;
case "/"
oper=new OperationDiv();
break;
}
return oper;
}
}
//客户端代码
Operation oper;
oper=OperationFactory.createOperate("+");
oper.Number1=1;
oper.Number2=2;
double result=oper.GetResult();