设计模式笔记(二)——简单工厂模式

 
  1. using System;
  2. using System.Collections.Generic;
  3. /**
  4.  * 简单工厂模式
  5.  */
  6. namespace StuDesignMode.SimpleFactory
  7. {
  8.     abstract class AbsOperation
  9.     {
  10.         public double NumA { getset; }
  11.         public double NumB { getset; }
  12.         public virtual double GetResult()
  13.         {
  14.             return 0;           
  15.         }
  16.     }
  17.     /// <summary>
  18.     /// 加法
  19.     /// </summary>
  20.     class OperationAdd:AbsOperation
  21.     {
  22.         public override double GetResult()
  23.         {
  24.             return this.NumA + this.NumB;
  25.         }
  26.     }
  27.     /// <summary>
  28.     /// 减法
  29.     /// </summary>
  30.     class OperationSub : AbsOperation
  31.     {
  32.         public override double GetResult()
  33.         {
  34.             return this.NumA - this.NumB;
  35.         }
  36.     }
  37.     /// <summary>
  38.     /// 乘法
  39.     /// </summary>
  40.     class OperationMul : AbsOperation
  41.     {
  42.         public override double GetResult()
  43.         {
  44.             return this.NumA * this.NumB;
  45.         }
  46.     }
  47.     /// <summary>
  48.     /// 除法
  49.     /// </summary>
  50.     class OperationDiv : AbsOperation
  51.     {
  52.         public override double GetResult()
  53.         {
  54.             double result = 0;
  55.             if (this.NumB == 0)
  56.             {
  57.                 throw new Exception("除数不能为0。");
  58.             }
  59.             result = this.NumA / this.NumB;
  60.             return result;
  61.         }
  62.     }
  63.     class OperationFactory
  64.     {
  65.         public static AbsOperation CreateOperate(string operate)
  66.         {
  67.             AbsOperation oper = null;
  68.             switch (operate)
  69.             {
  70.                 case "+":oper = new OperationAdd(); break;
  71.                 case "-": oper = new OperationSub(); break;
  72.                 case "*": oper = new OperationMul(); break;
  73.                 case "/": oper = new OperationDiv(); break;
  74.             }
  75.             return oper;
  76.         }
  77.     }
  78.     //客户端测试
  79.     class ClientTest
  80.     {
  81.         static void Main(string [] args)
  82.         {
  83.             AbsOperation oper = OperationFactory.CreateOperate("+");
  84.             oper.NumA = 1;
  85.             oper.NumB = 2;
  86.             double result = oper.GetResult();
  87.             Console.WriteLine(result);
  88.         }
  89.     }
  90. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值