学习笔录——设计模式
简单工厂模式
简介
用一个单独的类来负责实例化不同的对象。
代码示例
public abstract class Operation
{
public double NumA;
public double NumB;
public abstract double GetResult();
}
public class AddOperationSampleFactory : Operation
{
public override double GetResult()
{
return base.NumA + base.NumB;
}
}
public class SubOperationSampleFactory : Operation
{
public override double GetResult()
{
return base.NumA - base.NumB;
}
}
// 简单工厂
public static Operation CreateOperation(string oper)
{
Operation operation = null;
switch(oper)
{
case "+" :
operation = new AddOperationSampleFactory();
break;
case "-" :
operation = new SubOperationSampleFactory();
break;
default :
break;
}
return operation;
}
static void Main(string[] args)
{
// 简单工厂
var oper = OperationSampleFactory.CreateOperation("+");
oper.NumA = 1;
oper.NumB = 2;
oper.GetResult();
Console.Read();
}