重构研究:Replace Type Code with Subclasses(以子类取代类型码),

 

动机:

如果你的类中有一个不可变的类型码,它会影响类的行为

如果类中有一个标志,看起来像是switch这样,或者if-else if-else if这种结构,并且以后可能还要增加其他类型的标志,就可以使用这种重构方法

做法:

1.先使用Self Encapsulate Field(自封装字段)将类型码自我封装起来,如果类型码有在构造函数里赋值,就需要将构造函数改为工厂函数来创建对象

2.为类中的每一个标志建立一个子类,在每个子类中覆写类型码的get函数,返回相应的类型码

3.从超类中删掉保存标志的字段,将超类的get函数声明为抽象函数

示例:

 1 public class Employee {
 2 
 3     private static final int ENGINEER = 0;
 4 
 5     private static final int SALESMAN = 1;
 6 
 7     private int type;
 8     
 9     public Employee(int type) {
10         this.type = type;
11     }
12     
13     public int getType() {
14         return this.type;
15     }
16 }

修改后的代码为:

 1 public abstract class Employee {
 2 
 3     protected static final int ENGINEER = 0;
 4 
 5     protected static final int SALESMAN = 1;
 6 
 7     protected Employee() {
 8     }
 9 
10     public static Employee createEmployee(int type) {
11         switch (type) {
12         case ENGINEER: {
13             return new Engineer();
14         }
15         case SALESMAN: {
16             return new Salesman();
17         }
18         default: {
19             throw new RuntimeException("createEmployee error");
20         }
21         }
22     }
23 
24     protected abstract int getType();
25 }
 1 public class Engineer extends Employee {
 2 
 3     protected Engineer() {
 4         super();
 5         // TODO Auto-generated constructor stub
 6     }
 7 
 8     @Override
 9     protected int getType() {
10         // TODO Auto-generated method stub
11         return Employee.ENGINEER;
12     }
13 }
 1 public class Salesman extends Employee {
 2 
 3     protected Salesman() {
 4         super();
 5         // TODO Auto-generated constructor stub
 6     }
 7 
 8     @Override
 9     protected int getType() {
10         // TODO Auto-generated method stub
11         return Employee.SALESMAN;
12     }
13 }

 

这样以后想要增加一种方法就只要创建一个子类,然后修改一下父类的工厂函数就可以了,这种用于Replace Conditional with Polymorphism(用多态代替条件语句)或者用Replace Type Code with State/Strategy(用State/Strategy代替类型码)就方便了

posted on 2012-08-01 14:23  低调点  阅读(219)  评论(0)    收藏  举报

导航