8.14 replace type code with subclasses (以子类取代类型码)

有一个不可变的类型码,会影响类的行为。

以子类取代这个类型码。

动机:

如果类型码会影响宿主类的行为,那么最好的办法就是借助多态来处理变化行为。

以类型码的宿主类为基类,针对每种类型码建立相应的子类。

一下情况不能那么做:类型码值在对象创建之后发生了变化;由于某些原因,类型码宿主类已经有了子类。因此需要使用replace type code with state/strategy。

另一个原因是:宿主类中出现了“只与具备特定类型码之对象相关”的特性。可以使用push down method和push down field。

做法:

使用self encapsulate field将类型码自我封装起来。

=》如果类型码被传递给构造函数,就需要将构造函数换成工厂函数。

为类型码的每一个数值建立一个相应的子类。在每个子类中覆写类型码的取值函数,使其返回相应的类型码值。

=》这个值被硬编码return句中。这看起来很肮脏,但只是权宜之计。当所有case子句都被替换后,问题就解决了。

从超类中删除保存类型码的字段。将类型码访问函数声明为抽象函数。


旧代码

class Employee...
private int _type;
static final int ENGINEER = 0;
static final int SALESMAN = 1;
static final int MANAGER = 2;
Employee(int type){
    _type = type;
}



新代码

class Employee...
abstract int getType();
static employee create(int type){
    switch(type){
        case ENGINERR:
            return new Engineer();
        case SALESMAN:
            return new Salesman();
        case MANAGER:
            return new Manager();
        default:
            throw new IllegalArgumentException();
    }
    return new Employee(type);
}
private Employee(int type){
    _type = type;
}
class Engineer extends Employee{
    int getType(){
        return employee.ENGINEER;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值