你的位置:首页 > ASP.net教程

[ASP.net教程]《大话设计模式》学习笔记1:简单工厂模式


计算器示例:

  

1.运算类:

  public class Operation  {    public double NumberA { get; set; }    public double NumberB { get; set; }    public virtual double GetResult()    {
       return 0; } }

2.加减乘除类(以加法类为例):

  public class AddOperation:Operation  {    public override double GetResult()    {      return NumberA + NumberB;    }  }

3.简单工厂类:

  public class OperationFactory  {    public static Operation CreateOperate(string operate)    {      Operation oper;      switch(operate)      {        case "+":          oper = new AddOperation();          break;        case "-":          oper = new SubOperation();          break;        default :          oper = null;          break;      }      return oper;    }  }

4.客户端代码:

  class Program  {    static void Main(string[] args)    {      Operation oper = OperationFactory.CreateOperate("+");      oper.NumberA = 1;      oper.NumberB = 2;      Console.WriteLine(oper.GetResult());    }  }