工厂方法模式(Factory Pattern)
工厂方法模式对简单工厂模式进行改进,从工厂类中抽象出来一个接口用于创建实际工厂类,其uml图如下所示:
具体实现如下:
class Operation
{
private double _numberA = 0;
private double _numberB = 0;
public double NubmerA
{
get { return _numberA; }
set { _numberA = value; }
}
public double NumberB
{
get { return _numberB; }
set { _numberB = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
interface IFactory
{
Operation CreatOperation();
}
class OperationAdd : IFactory
{
public Operation CreatOperation()
{
return new OperationAdd();
}
public override double GetResult()
{
double result = 0;
result = NubmerA + NumberB;
return result;
}
}
class OperationSub : IFactory
{
public Operation CreatOperation()
{
return new OperationSub();
}
public override double GetResult()
{
double result = 0;
result = NubmerA - NumberB;
return result;
}
}
调用:
IFactory operFactory = new OperationAdd(); Operation oper = operFactory.CreatOperation(); oper.NubmerA = 1; oper.NumberB = 4; oper.GetResult();