using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//代码为大话设计模式书中的代码
namespace jiandangongchang
{
class Program
{
static void Main(string[] args)
{
Opreation oper;
oper = OpreationFactory.CreateOperate("/");//调用简单工厂,输入想要得到的产品(/)
oper.NumberA = 10;
oper.NumberB = 2;
Console.WriteLine(oper.GetResult());
}
}
public class Opreation//运算类父类
{
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:Opreation//加法类,只实现生产物品的单步骤操作
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
class OpreationSub : Opreation//减法类
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
class OpreationMul:Opreation//乘法类
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
class OpreationDiv:Opreation//除法类
{
public override double GetResult()
{
double result = 0;
if (NumberB==0)
{
return 0;
}
result = NumberA / NumberB;
return result;
}
}
public class OpreationFactory//简单工厂类,实现生产物品的操作,不会对物品产生修改
{
public static Opreation CreateOperate(string operate)
{
Opreation oper = null;
switch (operate)
{
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OpreationSub();
break;
case "*":
oper = new OpreationMul();
break;
case "/":
oper = new OpreationDiv();
break;
}
return oper;
}
}
}
简单工厂的理解:工厂相当于像是生活中的工厂,工厂负责生产物品,比如 家具中的 桌子,椅子,凳子,那么桌子椅子凳子都是木头做的,他们的刷漆都是一样的,他们有他们的共同的特性,只不过,在部件的形状以及组装方法上是不同的,所以在工厂中,可能会有三条流水线,一条是桌子,一条是椅子,一条是凳子,我在最源头放入所需要的木材,通过我想要得到的物品,放入对应的流水线上,那么生产出来就会是我需要的产品。
简单工厂的优点: 工厂类只负责生产,如果生产的“+”,“/”发生改变,不需要对工厂类进行修改,只需要修改 对应为生产产品的“+”类即可,如果想增加生产列表的话比如多增加“%”操作,是要定义“%”的产品类 以及 在工厂的生产列表中加入“%”的工作序列