工厂方法模式结构图:
简单工厂模式在创建操作符对象工厂时违背了开放-封闭原则:因此出现了工厂方法模式。
本例以两个数的加法和减法操作为例:
操作符类(OperateNum):
namespace Factory_Method_Pattern.CLASS { abstract class OperateNum { private decimal numberA; private decimal numberB; /// <summary> /// 操作数A /// </summary> public decimal NumberA { get { return numberA; } set { numberA = value; } } /// <summary> /// 操作数B /// </summary> public decimal NumberB { get { return numberB; } set { numberB = value; } } public abstract decimal Result(); } }
加法类(Add):继承于操作符类(OperateNum)
namespace Factory_Method_Pattern.CLASS { class Add:OperateNum { public override decimal Result() { decimal result; result = NumberA + NumberB; return result; } } }
减法类(Sub):继承于操作符类(OperateNum)
namespace Factory_Method_Pattern.CLASS { class Sub:OperateNum { public override decimal Result() { decimal result; result = NumberA - NumberB; return result; } } }
工厂接口(IFactory):
namespace Factory_Method_Pattern.CLASS { interface IFactory { OperateNum CreateOperate(); } }
加法工厂(AddFactory):继承于工厂接口(IFactory)
namespace Factory_Method_Pattern.CLASS { class AddFactory:IFactory { public OperateNum CreateOperate() { return new Add(); } } }
减法工厂(SubFactory):继承于工厂接口(IFactory)
namespace Factory_Method_Pattern.CLASS { class SubFactory:IFactory { public OperateNum CreateOperate() { return new Sub(); } } }
客户端代码:(TestMain)
namespace Factory_Method_Pattern { class TestMain { static void Main(string[] args) { IFactory operFactory = new AddFactory(); OperateNum oper = operFactory.CreateOperate(); oper.NumberA = 1; oper.NumberB = 2; Console.WriteLine("相加结果为:{0}",oper.Result()); IFactory operFactory1 = new SubFactory(); OperateNum oper1 = operFactory1.CreateOperate(); oper1.NumberA = Convert.ToDecimal(Console.ReadLine()); oper1.NumberB = Convert.ToDecimal(Console.ReadLine()); Console.WriteLine("相减结果为:{0}", oper1.Result()); Console.ReadLine(); } } }
要么忍,要么狠,要么滚!