简单工厂模式
C#代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
* 简单工厂
* 封装业务,使业务逻辑和界面逻辑分开,让它们之间的耦合度下降
* Operation类及其子类,都实现了可复用。
* 简单工厂模式的最大优点在于工厂类中包含了必要的逻辑依赖,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
* 但是,每当要增加功能时,都要修改OperationFactory中的switch语句,这样就违背了开放-封闭原则。
*/
namespace Calculater
{
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;
}
}
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;
}
}
//Client
class Program
{
static void Main(string[] args)
{
try
{
Operation oper;
oper = Oper
补充:Web开发 , ASP.Net ,