有一个不可变的类型码,它会影响类的行为
public class Employee {
static final int ENGINNER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
private int type;
public Employee(int type) {
this.type = type;
}
public int getType() {
return type;
}
}
重构:以子类取代类型码
public class Employee {
static final int ENGINNER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
private int type;
public Employee(int type) {
this.type = type;
}
public static Employee create(int type) {
switch(type) {
case ENGINNER: return new Engineer();
case SALESMAN: return new Salesman();
case MANAGER: return new Manager();
default:
throw new IllegalArgumentException("Incorrect type code value.");
}
}
public abstract int getType();
}
public class Engineer extends Employee {
public int getType() {
return Employee.ENGINNER;
}
}