工厂模式的优势:能承受更多的扩展,只要是类似的功能就可以进行扩。即添加具体类,并在工厂中添加调用新加的类的条件即可
1.首先建立抽象类,建立各个具体功能类,建立生成工厂,文件结构图如下。
2.各个文件代码
2.1 Operation代码(抽象类)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculate.Calculate { class Operation { private double _numberA = 0d; private double _numberB = 0d; private double _result = 0d; public double NumberA { get { return _numberA; } set { _numberA = value; } } public double NumberB { get { return _numberB; } set { _numberB = value; } } public double Result { get { return _result; } set { _result = value; } } public virtual double getResult() { double result = 0d; return result; } } }
2.2 OperationAdd代码(加法类)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculate.Calculate { class OperationAdd:Operation { public override double getResult() { Result = NumberA + NumberB; return Result; } } }
2.3 OperationSub代码(减法类)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculate.Calculate { class OperationSub : Operation { public override double getResult() { Result = NumberA - NumberB; return Result; } } }
2.4 OperationMul代码(乘法类)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculate.Calculate { class OperationMul : Operation { public override double getResult() { Result = NumberA * NumberB; return Result; } } }
2.4 OperationDiv代码(除法类)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculate.Calculate { class OperationDiv : Operation { public override double getResult() { if (NumberB!=0) { Result = NumberA / NumberB; } else { Result = -1; } return Result; } } }