任何类的设计都要遵循耦合性低,避免重复。
设计模式的目的主要有3易。让项目易维护,易扩展,易复用。
易维护: 修改某个功能,只要修改最少的部分,比如某个类的方法。
易扩展: 项目本来有加减乘除功能,现在要扩展 根号,取余功能。 要尽量的少改代码。
易复用: 要让设计的方法不管在 控制台应用程序,web应用程序 还是 Winform程序都能使用。
简单工厂模式:解决了对象的创建问题
Operator.cs 定义了几个类,实现了加减功能。 其中通过OpeartorFactor 根据操作符来实例相应的对象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 简单工厂模式
{
class Operation
{
private double _numberA = 0.0;
private double _numberB = 0.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.0;
return result;
}
}
class OpeartionAdd : Operation
{
public override double getResult()
{
double result = 0.0;
result = NumberA + NumberB;
return result;
}
}
class OpeartionDel : Operation
{
public override double getResult()
{
double result = 0.0;
result = NumberA - NumberB;
return result;
}
}
class OperationFactory
{
public static Operation createOpeartion(string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OpeartionAdd();
break;
case "-":
oper = new OpeartionDel();
break;
}
return oper;
}
}
}
现在想加入 乘除功能,那怎么办呢?
只要 先添加 2个类,并重写getResult()方法,然后再 工厂类中 加入 符号的判断
class OpeartionMul:Operation
class OpeartionDiv:Operation
case "*":
oper = new OpeartionMul();
break;
修改后的文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 简单工厂模式
{
class Operation
{
private double _numberA = 0.0;
private double _numberB = 0.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.0;
return result;
}
}
class OpeartionAdd : Operation
{
public override double getResult()
{
double result = 0.0;
result = NumberA + NumberB;
return result;
}
}
class OpeartionDel : Operation
{
public override double getResult()
{
double result = 0.0;
result = NumberA - NumberB;
return result;
}
}
class OpeartionMul : Operation
{
public override double getResult()
{
double result = 0.0;
result = NumberA * NumberB;
return result;
}
}
class OpeartionDiv : Operation
{
public override double getResult()
{
double result = 0.0;
result = NumberA / NumberB;
return result;
}
}
class OperationFactory
{
public static Operation createOpeartion(string operate)
{
Operation oper = null;
switch (operate)
{
case "+":
oper = new OpeartionAdd();
break;
case "-":
oper = new OpeartionDel();
break;
case "*":
oper = new OpeartionMul();
break;
case "/":
oper = new OpeartionDiv();
break;
}
return oper;
}
}
}
昂首阔步,不留一点遗憾