http://www.cnblogs.com/pfblog/p/7815238.html

 

最近在工作中优化了一段冗余的if else代码块,感觉对设计模式的理解和运用很有帮助,所以分享出来。鉴于原代码会涉及到公司的隐私,因此就不贴出来了。下面以更加通俗易懂的案例来解析。

假如写一个针对员工上班不遵守制度做相应惩罚的程序,比如,上班迟到:罚100;上班睡觉:罚1000;上班早退:警告;上班玩游戏:严重警告;上班谈恋爱:开除等,通常都会这样写:

代码重构:用工厂+策略模式优化过多的if else代码块
public class WorkPunish {
    public static void main(String[] agrs){
        String state ="late";
        punish(state);
    }
    
    public static void punish(String state){
        if ("late".equals(state)){
            System.out.println("罚100");
        }else if ("sleep".equals(state)){
            System.out.println("罚1000");
        }else if ("early".equals(state)){
            System.out.println("警告");
        }else if ("play".equals(state)){
            System.out.println("严重警告");
        }else if ("love".equals(state)){
            System.out.println("开除");
        }
    }
}
代码重构:用工厂+策略模式优化过多的if else代码块

可以看到,每增加一种情况都要增加一个if else判断,这样会造成这段代码非常长,可读性差、不易维护。下面就用静态工厂+策略模式来重构这段代码(对于静态工厂模式和策略模式不知道的同学请自行百度哈

先说说思路:1、定义一个处罚的接口 ,包含一个执行处罚的方法

      2、每一种情况的处罚都抽象成一个具体处罚类并继承处罚接口(策略模式)

      3、定义一个静态工厂类,用来根据情况生产具体处罚对象,然后执行处罚的方法(静态工厂模式)。

代码如下:

package com.test.punish;

public interface IPunish {
    void exePunish();
}

相关文章:

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