# 设计模式培训之二：简单工厂、工厂方法

1. 是面向过程的实现方法：

string strResult = "";
switch (Operate)
{
case "+":
strResult = Convert.toString(Convert.ToDouble(NumA) + Convert.ToDouble(NumB));
break;
case "-":
strResult = Convert.toString(Convert.ToDouble(NumA) - Convert.ToDouble(NumB));
break;
case "*":
strResult = Convert.toString(Convert.ToDouble(NumA) * Convert.ToDouble(NumB));
break;
case "/":
if (NumB != 0)
{
strResult = Convert.toString(Convert.ToDouble(NumA) + Convert.ToDouble(NumB));
}
else
{
strResult = "除数不能为0";
}
break;
}

2. 用简单工厂实现：

ULM图：

s

public abstract class Operation
{
public double NumA { get; set; }
public double NumB { get; set; }
public abstract double GetResult();
}

{
public override double GetResult()
{
return NumA + NumB;
}
}

public class OperationSub : Operation
{
public override double GetResult()
{
return NumA - NumB;
}
}

public class Factory
{
public Operation Create(string ope)
{
Operation operation=null;
switch(ope)
{
case "+":
break;
case "-":
operation=new OperationSub();
break;
}
return operation;
}
}

Operation oper;

oper=new Factory().Create("+");
oper.NumA=1;
oper.NumB=2;
double result=oper.GetResult();

3 用工厂方法实现：

UML图：

    public interface IFactory
{
Operation Create();
}
{
public Operation Create()
{
}
}
public class SubOperation : IFactory
{
public Operation Create()
{
return new OperationSub();
}
}

public abstract class Operation
{
public double NumA { get; set; }
public double NumB { get; set; }
public abstract double GetResult();
}
{
public override double GetResult()
{
return NumA + NumB;
}
}
public class OperationSub : Operation
{
public override double GetResult()
{
return NumA - NumB;
}
}

IFactory factory = new AddOperation();
Operation oper = factory.Create();
oper.NumA = 3;
oper.NumB = 2;
double result = oper.GetResult();

IFactory factory = new SubOperation();
Operation oper = factory.Create();
oper.NumA = 3;
oper.NumB = 2;
double result = oper.GetResult();

<appSettings>
</appSettings>

string factoryName = ConfigurationSettings.AppSettings["factoryName"];
IFactory factory = (IFactory)Assembly.Load("BLL").CreateInstance("BLL." + factoryName);
Operation oper = factory.Create();
oper.NumA = 3;
oper.NumB = 2;
double result = oper.GetResult();

posted @ 2012-05-02 14:16  赵学智  阅读(4171)  评论(4编辑  收藏  举报