目录

1.背景

2.案例

3.switch…case…方式实现

4.switch…case…带来的问题

5.使用策略模式重构switch…case…代码

6.总结

1.背景

          之前在看《重构    改善既有代码的设计》一书,在看到Replace Type Code With  State/Strategy(用状态模式/策略模式替换类型码)一节时遇到一个困惑:怎么用策略模式替换switch case代码?所幸的时,两天前查资料的时候偶然看到 圣殿骑士 的博客,他写的《31天重构学习》系列博客让我受益匪浅,也让我领悟到了怎么使用策略模式替换swith  case代码,并在此基础之上编写了一个Demo,以供分享、交流。

2.案例

         功能:简易计算器

         项目结构如图1

       使用策略模式重构switch case 代码

                        图1

         其中:StrategyPatternDemo为核心计算类库

         Calculator.Client为计算器客户端,是命令行程序

3.swich…case…方式实现

         StrategyPatternDemo类库里包括了IOperation(计算操作,如+-*/)和ICalculator(计算)两个接口以及Operation和Calculator两个实现类。

         具体实现代码如下:

 1 /// <summary>
 2 
 3     /// 计算操作接口
 4 
 5     /// </summary>
 6 
 7     public interface IOperation
 8 
 9     {
10 
11         #region 属性
12 
13         /// <summary>
14 
15         /// 操作名称
16 
17         /// </summary>
18 
19         string Name { get; }
20 
21         /// <summary>
22 
23         /// 操作符号
24 
25         /// </summary>
26 
27         string Symbol { get; }
28 
29         /// <summary>
30 
31         /// 操作数量
32 
33         /// </summary>
34 
35         int NumberOperands { get; }
36 
37         #endregion
38 
39     }
IOperation

相关文章:

  • 2021-10-30
  • 2022-12-23
  • 2021-10-31
  • 2021-11-24
  • 2021-06-12
  • 2021-07-28
猜你喜欢
  • 2021-09-22
  • 2022-12-23
  • 2021-05-28
  • 2021-12-08
  • 2022-12-23
  • 2022-01-06
相关资源
相似解决方案