Loading

简单工厂模式

客户端代码:

   1:          static void Main(string[] args)
   2:          {
   3:              Operator p = OperatorFactory.CreateOperate("+");
   4:              Console.WriteLine(p.GetResult());
   5:              Console.ReadLine();
   6:          }

服务端代码:

   1:  using System; 
   2:  using System.Collections.Generic; 
   3:  using System.Linq; 
   4:  using System.Text; 
   5:   
   6:  namespace CalculatorProgram 
   7:  { 
   8:      class Operator 
   9:      { 
  10:   
  11:          public double numA 
  12:          { 
  13:              get; 
  14:              set; 
  15:          } 
  16:   
  17:          public double numB 
  18:          { 
  19:              get; 
  20:              set; 
  21:          } 
  22:   
  23:          public virtual double GetResult() 
  24:          { 
  25:              return 0; 
  26:          } 
  27:      } 
  28:   
  29:      class AddOperator : Operator 
  30:      { 
  31:          public override double GetResult() 
  32:          { 
  33:              return numA + numB; 
  34:          } 
  35:      } 
  36:   
  37:      class SubOperator : Operator 
  38:      { 
  39:          public override double GetResult() 
  40:          { 
  41:              return numA - numB; 
  42:          } 
  43:      } 
  44:   
  45:      class OperatorFactory 
  46:      { 
  47:          public static Operator CreateOperate(string oper) 
  48:          { 
  49:              switch (oper) 
  50:              { 
  51:                  case "+": 
  52:                      return new AddOperator(); 
  53:                  case "-": 
  54:                      return new SubOperator(); 
  55:                  default: 
  56:                      return null; 
  57:              } 
  58:          } 
  59:      } 

posted @ 2008-09-17 16:55  today4king  阅读(226)  评论(0编辑  收藏  举报