标签:style blog class code c tar
从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现。
实现方式(附图)
UML图
class Program { static void Main(string[] args) { Operation oper; oper = OperationFactory.CreateOperation("4"); if(oper!=null) { oper.NumberA = 1; oper.NumberB = 2; Console.WriteLine(oper.GetResult()); } Console.ReadLine(); } } #region //简单工厂类 public class OperationFactory { public static Operation CreateOperation(string operation) { Operation oper = null; switch (operation) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } } #endregion #region//运算类Operation 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; } } #endregion #region//继承运算类 public class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } } public class OperationSub : Operation { public override double GetResult() { double result = 0; result = NumberA - NumberB; return result; } } public class OperationMul : Operation { public override double GetResult() { double result = 0; result = NumberA * NumberB; return result; } } public class OperationDiv : Operation { public override double GetResult() { double result = 0; result = NumberA / NumberB; return result; } } #endregion
简单工厂就是把new脱离出来,延迟到子类里做处理。然后通过工厂类做判断哪种情况对应哪个子类。
适当的时候,Factory可以做成配置文件进行处理。
标签:style blog class code c tar
原文地址:http://www.cnblogs.com/xkdsz/p/3715038.html