重构第八章
15.Replace Type Code with State/Strategy(以state/strategy取代型别码)
你有一个type code,它会影响class的行为,但你无法使用subclassing。以state object(专门用来描述状态的对象)取代type code。
Example:
class Emplouee {
private int _type;
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
Employee (int type) {
_type = type;
}
int payAmount() {
switch(_type) {
case ENGINEER: return _monthlySalary;
case SALESMAN: return _monthlySalary + _commission;
case MANAGER: return _monthlySalary + _bonus;
default:
throw new RuntimeException("Incorrect Employee");
}
}
}
Analyse:
Replace Type Code With Subclasses(以子类取代型别码)在上一节中,将类型码和子类相替换,对象和类型码绑定。如果此时一位工程师由于表现优异,提拔为了经理,那这样的调整在上一节中不是那么容易可以实现的。所以,如果对象的type code是可变的,我们不能使用subclasses的方法来处理type code。
End:
class Engineer extends EmployeeType {
int getTypeCode() {
return Employee.ENGINEER;
}
}
class Salesman extends EmployeeType {
int getTypeCode() {
return Employee.SALESMAN;
}
}
class Manager extends EmployeeType {
int getTypeCode() {
return Employee.MANAGER;
}
}
class EmployeeType...
static EmployeeType new Type(int code) {
switch(code) {
case ENGINEER:
return new Engineer();
case SALESMAN:
return new Salesman();
case MANAGER:
return new Manager();
default:
throw new IllegalArgumenTException("Incurrect Employee Code");
}
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
}
class Employee...
int getType() {
_type.getTypeCode();
}
void setType(int arg) {
_type = EmployeeType.newType(arg);
}
int payAmount() {
switch(getType()) {
case EmployeeType.ENGINEER:
return _monthlySalary;
case EmployeeType.SALESMAN:
return _monthlySalary + _commission;
case EmployeeType.MANAGER:
return _monthlySalary + _bonus;
default:
throw new RutimeException("Incorrent Employee");
}
}
Conclusion:
Replace Type Code with State/Strategy(以state/strategy取代型别码)和Replace Type Code With Subclasses(以子类取代型别码)十分的类似,都是通过多态的方式,将type code绑定到固定的子类上面,其中不同的是,Replace Type Code With Subclasses(以子类取代型别码)绑定的是对象的子类,可以增添某种type特有的特性。而Replace Type Code with State/Strategy(以state/strategy取代型别码)绑定的是表示状态的类的子类,可以在运行中根据需求变换。
注意
重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!
网友评论