简单工厂模式
简单工厂模式又称静态工厂方法模式。重命名上就可以看出这个模式一定很简单。它存在的目的很简单:定义一个用于创建对象的接口。
简单工厂模式的组成:
1) 工厂类角色:这是本模式的核心,含有一定的商业逻辑和判断逻辑。
2) 抽象产品角色:它一般是具体产品继承的父类或者实现的接口。
3) 具体产品角色:工厂类所创建的对象就是此角色的实例。
计算机中业务的封装:
<span style="font-size:24px;">//operation运算类
public class Operation
{
public static double GetResult(double numberA, double numberB, string operate)
{
//定义一个double的变量
double result = 0d;
//选择判断
switch (operate)
{
case "+":
result = numberA + numberB;
break;
case "-":
result = numberA - numberB;
break;
case "*":
result = numberA * numberB;
break;
case "/":
result = numberA / numberB;
break;
}
return result;
}
}
//客户端代码
static void Main(string[] args)
{
try
{
Console.Write("请输入数字A:");
string strnumberA = Console.ReadLine();
Console.Write("请选择运算符号(+、-、*、/):");
string stroperate = Console.ReadLine();
Console.Write("请输入数字B:");
string strnumberB = Console.ReadLine();
string strresult = "";
strresult = Convert.ToString(Operation.GetResult(Convert.ToDouble(strnumberA),
Convert.ToDouble(strnumberB), stroperate));
Console.WriteLine("结果是:" + strresult);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("您的输入有误:" + ex.Message);
}
}
</span>
把其中的加减乘除运算分离,修改其中的一个不会影响到另外的几个,增加运算算法也不影响其他代码,程序如下:
<span style="font-size:24px;">//Operation运算类
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;
if (NumberB ==0)
throw new Exception ("除数不能为0。");
result =NumberA /NumberB ;
return result ;
}
}
</span>
简单工厂模式的设计与实现:
<span style="font-size:24px;">//简单运算工厂类
public class OperationFactory
{
public static Operation creatOperate(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.creatOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
}
</span>
首先,使用了简单工厂模式后,我们的程序不在“有病”,更加符合现实中的情况,而且,客户端免除了直接创建产品对象的责任,而仅仅负责“消费”产品。