
```
class Order {
get daysToShip() {
return this._warehouse.daysToShip;
}
}
class PriorityOrder extends Order {
get daysToShip() {
return this._priorityPlan.daysToShip;
}
}
```

```
class Order {
get daysToShip() {
return (this._priorityDelegate)
? this._priorityDelegate.daysToShip
: this._warehouse.daysToShip;
}
}
class PriorityOrderDelegate {
get daysToShip() {
return this._priorityPlan.daysToShip
}
}
```
### 动机
如果一个对象的行为有明显的类别之分,继承是很自然的表达方式。我可以把共用的数据和行为放在超类中,每个子类根据需要覆写部分特性。在面向对象语言中,继承很容易实现,因此也是程序员熟悉的机制。
但继承也有其短板。最明显的是,继承这张牌只能打一次。导致行为不同的原因可能有多种,但继承只能用于处理一个方向上的变化。比如说,我可能希望“人”的行为根据“年龄段”不同,并且根据“收入水平”不同。使用继承的话,子类可以是“年轻人”和“老人”,也可以是“富人”和“穷人”,但不能同时采用两种继承方式。
更大的问题在于,继承给类之间引入了非常紧密的关系。在超类上做任何修改,都很可能破坏子类,所以我必须非常小心,并且充分理解子类如何从超类派生。如果两个类的逻辑分处不同的模块、由不同的团队负责,问题就会更麻烦。
这两个问题用委托都能解决。对于不同的变化原因,我可以委托给不同的类。委托是对象之间常规的关系。与继承关系相比,使用委托关系时接口更清晰、耦合更少。因此,继承关系遇到问题时运用以委托取代子类是常见的情况。
有一条流行的原则:“对象组合优于类继承”(“组合”跟“委托”是同一回事)。很多人把这句话解读为“继承有害”,并因此声称绝不应该使用继承。我经常使用继承,部分是因为我知道,如果稍后需要改变,我总可以使用以委托取代子类。继承是一种很有价值的机制,大部分时候能达到效果,不会带来问题。所以我会从继承开始,如果开始出现问题,再转而使用委托。这种用法与前面说的原则实际上是一致的——这条出自名著《设计模式》\[gof\]的原则解释了如何让继承和组合协同工作。这条原则之所以强调“组合优于继承”,其实是对彼时继承常被滥用的回应。
熟悉《设计模式》一书的读者可以这样来理解本重构手法,就是用状态(State)模式或者策略(Strategy)模式取代子类。这两个模式在结构上是相同的,都是由宿主对象把责任委托给另一个继承体系。以委托取代子类并非总会需要建立一个继承体系来接受委托(下面第一个例子就没有),不过建立一个状态或策略的继承体系经常都是有用的。
### 做法
- 如果构造函数有多个调用者,首先用以工厂函数取代构造函数(334)把构造函数包装起来。
- 创建一个空的委托类,这个类的构造函数应该接受所有子类特有的数据项,并且经常以参数的形式接受一个指回超类的引用。
- 在超类中添加一个字段,用于安放委托对象。
- 修改子类的创建逻辑,使其初始化上述委托字段,放入一个委托对象的实例。
> 这一步可以在工厂函数中完成,也可以在构造函数中完成(如果构造函数有足够的信息以创建正确的委托对象的话)。
- 选择一个子类中的函数,将其移入委托类。
- 使用搬移函数(198)手法搬移上述函数,不要删除源类中的委托代码。
> 如果这个方法用到的其他元素也应该被移入委托对象,就把它们一并搬移。如果它用到的元素应该留在超类中,就在委托对象中添加一个字段,令其指向超类的实例。
- 如果被搬移的源函数还在子类之外被调用了,就把留在源类中的委托代码从子类移到超类,并在委托代码之前加上卫语句,检查委托对象存在。如果子类之外已经没有其他调用者,就用移除死代码(237)去掉已经没人使用的委托代码。
> 如果有多个委托类,并且其中的代码出现了重复,就使用提炼超类(375)手法消除重复。此时如果默认行为已经被移入了委托类的超类,源超类的委托函数就不再需要卫语句了。
- 测试。
- 重复上述过程,直到子类中所有函数都搬到委托类。
- 找到所有调用子类构造函数的地方,逐一将其改为使用超类的构造函数。
- 测试。
- 运用移除死代码(237)去掉子类。
### 范例
下面这个类用于处理演出(show)的预订(booking)。
##### class Booking...
```
constructor(show, date) {
this._show = show;
this._date = date;
}
```
它有一个子类,专门用于预订高级(premium)票,这个子类要考虑各种附加服务(extra)。
##### class PremiumBooking extends Booking...
```
constructor(show, date, extras) {
super(show, date);
this._extras = extras;
}
```
`PremiumBooking`类在超类基础上做了好些改变。在这种“针对差异编程”(programming-by-difference)的风格中,子类常会覆写超类的方法,有时还会添加只对子类有意义的新方法。我不打算讨论所有差异点,只选几处有意思的案例来分析。
先来看一处简单的覆写。常规票在演出结束后会有“对话创作者”环节(talkback),但只在非高峰日提供这项服务。
##### class Booking...
```
get hasTalkback() {
return this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}
```
`PremiumBooking`覆写了这个逻辑,任何一天都提供与创作者的对话。
##### class PremiumBooking...
```
get hasTalkback() {
return this._show.hasOwnProperty('talkback');
}
```
定价逻辑也是相似的覆写,不过略有不同:`PremiumBooking`调用了超类中的方法。
##### class Booking...
```
get basePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return result;
}
```
##### class PremiumBooking...
```
get basePrice() {
return Math.round(super.basePrice + this._extras.premiumFee);
}
```
最后一个例子是`PremiumBooking`提供了一个超类中没有的行为。
##### class PremiumBooking...
```
get hasDinner() {
return this._extras.hasOwnProperty('dinner') && !this.isPeakDay;
}
```
继承在这个例子中工作良好。即使不了解子类,我同样也可以理解超类的逻辑。子类只描述自己与超类的差异——既避免了重复,又清晰地表述了自己引入的差异。
说真的,它也并非如此完美。超类的一些结构只在特定的子类存在时才有意义——有些函数的组织方式完全就是为了方便覆写特定类型的行为。所以,尽管大部分时候我可以修改超类而不必理解子类,但如果刻意不关注子类的存在,在修改超类时偶尔有可能会破坏子类。不过,如果这种“偶尔”发生得不太频繁,继承就还是划算的——只要我有良好的测试,当子类被破坏时就能及时发现。
那么,既然情况还算不坏,为什么我想用以委托取代子类来做出改变呢?因为继承只能使用一次,如果我有别的原因想使用继承,并且这个新的原因比“高级预订”更有必要,就需要换一种方式来处理高级预订。另外,我可能需要动态地把普通预订升级成高级预订,例如提供`aBooking.bePremium()`这样一个函数。有时我可以新建一个对象(就好像通过HTTP请求从服务器端加载全新的数据),从而避免“对象本身升级”的问题。但有时我需要修改数据本身的结构,而不重建整个数据结构。如果一个`Booking`对象被很多地方引用,也很难将其整个替换掉。此时,就有必要允许在“普通预订”和“高级预订”之间来回转换。
当这样的需求积累到一定程度时,我就该使用以委托取代子类了。现在客户端直接调用两个类的构造函数来创建不同的预订。
##### 进行普通预订的客户端
`aBooking = new Booking(show,date);`##### 进行高级预订的客户端
`aBooking = new PremiumBooking(show, date, extras);`去除子类会改变对象创建的方式,所以我要先用以工厂函数取代构造函数(334)把构造函数封装起来。
##### 顶层作用域...
```
function createBooking(show, date) {
return new Booking(show, date);
}
function createPremiumBooking(show, date, extras) {
return new PremiumBooking (show, date, extras);
}
```
##### 进行普通预订的客户端
`aBooking = createBooking(show, date);`##### 进行高级预订的客户端
`aBooking = createPremiumBooking(show, date, extras);`然后新建一个委托类。这个类的构造函数参数有两部分:首先是指向`Booking`对象的反向引用,随后是只有子类才需要的那些数据。我需要传入反向引用,是因为子类的几个函数需要访问超类中的数据。有继承关系的时候,访问这些数据很容易;而在委托关系中,就得通过反向引用来访问。
##### class PremiumBookingDelegate...
```
constructor(hostBooking, extras) {
this._host = hostBooking;
this._extras = extras;
}
```
现在可以把新建的委托对象与`Booking`对象关联起来。在“创建高级预订”的工厂函数中修改即可。
##### 顶层作用域...
```
function createPremiumBooking(show, date, extras) {
const result = new PremiumBooking (show, date, extras);
result._bePremium(extras);
return result;
}
```
##### class Booking...
```
_bePremium(extras) {
this._premiumDelegate = new PremiumBookingDelegate(this, extras);
}
```
`_bePremium`函数以下划线开头,表示这个函数不应该被当作`Booking`类的公共接口。当然,如果最终我们希望允许普通预订转换成高级预订,这个函数也可以成为公共接口。
> 或者我也可以在`Booking`类的构造函数中构建它与委托对象之间的联系。为此,我需要以某种方式告诉构造函数“这是一个高级预订”:可以通过一个额外的参数,也可以直接通过`extras`参数来表示(如果我能确定这个参数只有高级预订才会用到的话)。不过我还是更愿意在工厂函数中构建这层联系,因为这样可以把意图表达得更明确。
结构设置好了,现在该动手搬移行为了。我首先考虑`hasTalkback`函数简单的覆写逻辑。现在的代码如下。
##### class Booking...
```
get hasTalkback() {
return this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}
```
##### class PremiumBooking...
```
get hasTalkback() {
return this._show.hasOwnProperty('talkback');
}
```
我用搬移函数(198)把子类中的函数搬到委托类中。为了让它适应新家,原本访问超类中数据的代码,现在要改为调用`_host`对象。
##### class PremiumBookingDelegate...
```
get hasTalkback() {
return this._host._show.hasOwnProperty('talkback');
}
```
##### class PremiumBooking...
```
get hasTalkback() {
return this._premiumDelegate.hasTalkback;
}
```
测试,确保一切正常,然后把子类中的函数删掉:
##### class PremiumBooking...
```
get hasTalkback() {
return this._premiumDelegate.hasTalkback;
}
```
再次测试,现在应该有一些测试失败,因为原本有些代码会用到子类上的`hasTalkback`函数。
现在我要修复这些失败的测试:在超类的函数中添加适当的分发逻辑,如果有代理对象存在就使用代理对象。这样,这一步重构就算完成了。
##### class Booking...
```
get hasTalkback() {
return (this._premiumDelegate)
? this._premiumDelegate.hasTalkback
: this._show.hasOwnProperty('talkback') && !this.isPeakDay;
}
```
下一个要处理的是`basePrice`函数。
##### class Booking...
```
get basePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return result;
}
```
##### class PremiumBooking...
```
get basePrice() {
return Math.round(super.basePrice + this._extras.premiumFee);
}
```
情况大致相同,但有一点儿小麻烦:子类中调用了超类中的同名函数(在这种“子类扩展超类行为”的用法中,这种情况很常见)。把子类的代码移到委托类时,需要继续调用超类的逻辑——但我不能直接调用`this._host.basePrice`,这会导致无穷递归,因为`_host`对象就是`PremiumBooking`对象自己。
有两个办法来处理这个问题。一种办法是,可以用提炼函数(106)把“基本价格”的计算逻辑提炼出来,从而把分发逻辑与价格计算逻辑拆开。(剩下的操作就跟前面的例子一样了。)
##### class Booking...
```
get basePrice() {
return (this._premiumDelegate)
? this._premiumDelegate.basePrice
: this._privateBasePrice;
}
get _privateBasePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return result;
}
```
##### class PremiumBookingDelegate...
```
get basePrice() {
return Math.round(this._host._privateBasePrice + this._extras.premiumFee);
}
```
另一种办法是,可以重新定义委托对象中的函数,使其成为基础函数的扩展。
##### class Booking...
```
get basePrice() {
let result = this._show.price;
if (this.isPeakDay) result += Math.round(result * 0.15);
return (this._premiumDelegate)
? this._premiumDelegate.extendBasePrice(result)
: result;
}
```
##### class PremiumBookingDelegate...
```
extendBasePrice(base) {
return Math.round(base + this._extras.premiumFee);
}
```
两种办法都可行,我更偏爱后者一点儿,因为需要的代码较少。
最后一个例子是一个只存在于子类中的函数。
##### class PremiumBooking...
```
get hasDinner() {
return this._extras.hasOwnProperty('dinner') && !this.isPeakDay;
}
```
我把它从子类移到委托类。
##### class PremiumBookingDelegate...
```
get hasDinner() {
return this._extras.hasOwnProperty('dinner') && !this._host.isPeakDay;
}
```
然后在`Booking`类中添加分发逻辑。
##### class Booking...
```
get hasDinner() {
return (this._premiumDelegate)
? this._premiumDelegate.hasDinner
: undefined;
}
```
在JavaScript中,如果尝试访问一个没有定义的属性,就会得到`undefined`,所以我在这个函数中也这样做。(尽管我直觉认为应该抛出错误,我所熟悉的其他面向对象动态语言就是这样做的。)
所有的行为都从子类中搬移出去之后,我就可以修改工厂函数,令其返回超类的实例。再次运行测试,确保一切都运转良好,然后我就可以删除子类。
##### 顶层作用域...
```
function createPremiumBooking(show, date, extras) {
const result = new PremiumBooking (show, date, extras);
result._bePremium(extras);
return result;
}
class PremiumBooking extends Booking ...
```
只看这个重构本身,我并不觉得代码质量得到了提升。继承原本很好地应对了需求场景,换成委托以后,我增加了分发逻辑、双向引用,复杂度上升不少。不过这个重构可能还是值得的,因为现在“是否高级预订”这个状态可以改变了,并且我也可以用继承来达成其他目的了。如果有这些需求的话,去除原有的继承关系带来的损失可能还是划算的。
### 范例:取代继承体系
前面的例子展示了如何用以委托取代子类去除单个子类。还可以用这个重构手法去除整个继承体系。
```
function createBird(data) {
switch (data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallow(data);
case 'AfricanSwallow':
return new AfricanSwallow(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrot(data);
default:
return new Bird(data);
}
}
class Bird {
constructor(data) {
this._name = data.name;
this._plumage = data.plumage;
}
get name() {return this._name;}
get plumage() {
return this._plumage || "average";
}
get airSpeedVelocity() {return null;}
}
class EuropeanSwallow extends Bird {
get airSpeedVelocity() {return 35;}
}
class AfricanSwallow extends Bird {
constructor(data) {
super (data);
this._numberOfCoconuts = data.numberOfCoconuts;
}
get airSpeedVelocity() {
return 40 - 2 * this._numberOfCoconuts;
}
}
class NorwegianBlueParrot extends Bird {
constructor(data) {
super (data);
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
get plumage() {
if (this._voltage > 100) return "scorched";
else return this._plumage || "beautiful";
}
get airSpeedVelocity() {
return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}
}
```
上面这个关于鸟儿(bird)的系统很快要有一个大变化:有些鸟是“野生的”(wild),有些鸟是“家养的”(captive),两者之间的行为会有很大差异。这种差异可以建模为`Bird`类的两个子类:`WildBird`和`CaptiveBird`。但继承只能用一次,所以如果想用子类来表现“野生”和“家养”的差异,就得先去掉关于“不同品种”的继承关系。
在涉及多个子类时,我会一次处理一个子类,先从简单的开始——在这里,最简单的当属`EuropeanSwallow`(欧洲燕)。我先给它建一个空的委托类。
```
class EuropeanSwallowDelegate {
}
```
委托类中暂时还没有传入任何数据或反向引用。在这个例子里,我会在需要时再引入这些参数。
现在需要决定如何初始化委托字段。由于构造函数接受的唯一参数`data`包含了所有的信息,我决定在构造函数中初始化委托字段。考虑到有多个委托对象要添加,我会建一个函数,其中根据类型码(`data.type`)来选择适当的委托对象。
##### class Bird...
```
constructor(data) {
this._name = data.name;
this._plumage = data.plumage;
this._speciesDelegate = this.selectSpeciesDelegate(data);
}
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
default: return null;
}
}
```
结构设置完毕,我可以用搬移函数(198)把`EuropeanSwallow`的`airSpeedVelocity`函数搬到委托对象中。
##### class EuropeanSwallowDelegate...
`get airSpeedVelocity() {return 35;}`##### class EuropeanSwallow...
`get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}`修改超类的`airSpeedVelocity`函数,如果发现有委托对象存在,就调用之。
##### class Bird...
```
get airSpeedVelocity() {
return this._speciesDelegate ? this._speciesDelegate.airSpeedVelocity : null;
}
```
然后,删除子类。
```
class EuropeanSwallow extends Bird {
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
}
```
##### 顶层作用域...
```
function createBird(data) {
switch (data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallow(data);
case 'AfricanSwallow':
return new AfricanSwallow(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrot(data);
default:
return new Bird(data);
}
}
```
接下来处理`AfricanSwallow`(非洲燕)子类。为它创建一个委托类,这次委托类的构造函数需要传入`data`参数。
##### class AfricanSwallowDelegate...
```
constructor(data) {
this._numberOfCoconuts = data.numberOfCoconuts;
}
```
##### class Bird…
```
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data);
default: return null;
}
}
```
同样用搬移函数(198)把`airSpeedVelocity`搬到委托类中。
##### class AfricanSwallowDelegate...
```
get airSpeedVelocity() {
return 40 - 2 * this._numberOfCoconuts;
}
```
##### class AfricanSwallow...
```
get airSpeedVelocity() {
return this._speciesDelegate.airSpeedVelocity;
}
```
再删掉`AfricanSwallow`子类。
```
class AfricanSwallow extends Bird {
// all of the body ...
}
function createBird(data) {
switch (data.type) {
case 'AfricanSwallow':
return new AfricanSwallow(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrot(data);
default:
return new Bird(data);
}
}
```
接下来是`NorwegianBlueParrot`(挪威蓝鹦鹉)子类。创建委托类和搬移`airSpeed Velocity`函数的步骤都跟前面一样,所以我直接展示结果好了。
##### class Bird...
```
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data);
default: return null;
}
}
```
##### class NorwegianBlueParrotDelegate...
```
constructor(data) {
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
get airSpeedVelocity() {
return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}
```
一切正常。但`NorwegianBlueParrot`还覆写了`plumage`属性,前面两个例子则没有。首先我还是用搬移函数(198)把`plumage`函数搬到委托类中,这一步不难,不过需要修改构造函数,放入对`Bird`对象的反向引用。
##### class NorwegianBlueParrot...
```
get plumage() {
return this._speciesDelegate.plumage;
}
```
##### class NorwegianBlueParrotDelegate...
```
get plumage() {
if (this._voltage > 100) return "scorched";
else return this._bird._plumage || "beautiful";
}
constructor(data, bird) {
this._bird = bird;
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
```
##### class Bird...
```
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate();
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data, this);
default: return null;
}
}
```
麻烦之处在于如何去掉子类中的`plumage`函数。如果我像下面这么干就会得到一大堆错误,因为其他品种的委托类没有`plumage`这个属性。
##### class Bird...
```
get plumage() {
if (this._speciesDelegate)
return this._speciesDelegate.plumage;
else
return this._plumage || "average";
}
```
我可以做一个更明确的条件分发:
##### class Bird...
```
get plumage() {
if (this._speciesDelegate instanceof NorwegianBlueParrotDelegate)
return this._speciesDelegate.plumage;
else
return this._plumage || "average";
}
```
不过我超级反感这种做法,希望你也能闻出同样的坏味道。像这样的显式类型检查几乎总是坏主意。
另一个办法是在其他委托类中实现默认的行为。
##### class Bird...
```
get plumage() {
if (this._speciesDelegate)
return this._speciesDelegate.plumage;
else
return this._plumage || "average";
}
```
##### class EuropeanSwallowDelegate...
```
get plumage() {
return this._bird._plumage || "average";
}
```
##### class AfricanSwallowDelegate...
```
get plumage() {
return this._bird._plumage || "average";
}
```
但这又造成了`plumage`默认行为的重复。如果这还不够糟糕的话,还有一个“额外奖励”:构造函数中给`_bird`反向引用赋值的代码也会重复。
解决重复的办法,很自然,就是继承——用提炼超类(375)从各个代理类中提炼出一个共同继承的超类。
```
class SpeciesDelegate {
constructor(data, bird) {
this._bird = bird;
}
get plumage() {
return this._bird._plumage || "average";
}
class EuropeanSwallowDelegate extends SpeciesDelegate {
class AfricanSwallowDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data,bird);
this._numberOfCoconuts = data.numberOfCoconuts;
}
class NorwegianBlueParrotDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data, bird);
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
```
有了共同的超类以后,就可以把`SpeciesDelegate`字段默认设置为这个超类的实例,并把`Bird`类中的默认行为搬移到`SpeciesDelegate`超类中。
##### class Bird...
```
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate(data, this);
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data, this);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data, this);
default: return new SpeciesDelegate(data, this);
}
}
// rest of bird’s code...
get plumage() {return this._speciesDelegate.plumage;}
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
```
##### class SpeciesDelegate...
`get airSpeedVelocity() {return null;}`我喜欢这种办法,因为它简化了`Bird`类中的委托函数。我可以一目了然地看到哪些行为已经被委托给`SpeciesDelegate`,哪些行为还留在`Bird`类中。
这几个类最终的状态如下:
```
function createBird(data) {
return new Bird(data);
}
class Bird {
constructor(data) {
this._name = data.name;
this._plumage = data.plumage;
this._speciesDelegate = this.selectSpeciesDelegate(data);
}
get name() {return this._name;}
get plumage() {return this._speciesDelegate.plumage;}
get airSpeedVelocity() {return this._speciesDelegate.airSpeedVelocity;}
selectSpeciesDelegate(data) {
switch(data.type) {
case 'EuropeanSwallow':
return new EuropeanSwallowDelegate(data, this);
case 'AfricanSwallow':
return new AfricanSwallowDelegate(data, this);
case 'NorweigianBlueParrot':
return new NorwegianBlueParrotDelegate(data, this);
default: return new SpeciesDelegate(data, this);
}
}
// rest of bird’s code...
}
class SpeciesDelegate {
constructor(data, bird) {
this._bird = bird;
}
get plumage() {
return this._bird._plumage || "average";
}
get airSpeedVelocity() {return null;}
}
class EuropeanSwallowDelegate extends SpeciesDelegate {
get airSpeedVelocity() {return 35;}
}
class AfricanSwallowDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data,bird);
this._numberOfCoconuts = data.numberOfCoconuts;
}
get airSpeedVelocity() {
return 40 - 2 * this._numberOfCoconuts;
}
}
class NorwegianBlueParrotDelegate extends SpeciesDelegate {
constructor(data, bird) {
super(data, bird);
this._voltage = data.voltage;
this._isNailed = data.isNailed;
}
get airSpeedVelocity() {
return (this._isNailed) ? 0 : 10 + this._voltage / 10;
}
get plumage() {
if (this._voltage > 100) return "scorched";
else return this._bird._plumage || "beautiful";
}
}
```
在这个例子中,我用一系列委托类取代了原来的多个子类,与原来非常相似的继承结构被转移到了`SpeciesDelegate`下面。除了给`Bird`类重新被继承的机会,从这个重构中我还有什么收获?新的继承体系范围更收拢了,只涉及各个品种不同的数据和行为,各个品种相同的代码则全都留在了`Bird`中,它未来的子类也将得益于这些共用的行为。
在前面的“演出预订”的例子中,我也可以采用同样的手法,创建一个委托超类。这样在`Booking`类中就不需要分发逻辑,直接调用委托对象即可,让继承关系来搞定分发。不过写到这儿,我要去吃晚饭了,就把这个练习留给读者吧。
从这两个例子看来,“对象组合优于类继承”这句话更确切的表述可能应该是“审慎地组合使用对象组合与类继承,优于单独使用其中任何一种”——不过这就不太上口了。
- 第1章 重构,第一个示例
- 1.1 起点
- 1.2 对此起始程序的评价
- 1.3 重构的第一步
- 1.4 分解statement函数
- 1.5 进展:大量嵌套函数
- 1.6 拆分计算阶段与格式化阶段
- 1.7 进展:分离到两个文件(和两个阶段)
- 1.8 按类型重组计算过程
- 1.9 进展:使用多态计算器来提供数据
- 1.10 结语
- 第2章 重构的原则
- 2.1 何谓重构
- 2.2 两顶帽子
- 2.3 为何重构
- 2.4 何时重构
- 2.5 重构的挑战
- 2.6 重构、架构和YAGNI
- 2.7 重构与软件开发过程
- 2.8 重构与性能
- 2.9 重构起源何处
- 2.10 自动化重构
- 2.11 延展阅读
- 第3章 代码的坏味道
- 3.1 神秘命名(Mysterious Name)
- 3.2 重复代码(Duplicated Code)
- 3.3 过长函数(Long Function)
- 3.4 过长参数列表(Long Parameter List)
- 3.5 全局数据(Global Data)
- 3.6 可变数据(Mutable Data)
- 3.7 发散式变化(Divergent Change)
- 3.8 霰弹式修改(Shotgun Surgery)
- 3.9 依恋情结(Feature Envy)
- 3.10 数据泥团(Data Clumps)
- 3.11 基本类型偏执(Primitive Obsession)
- 3.12 重复的switch (Repeated Switches)
- 3.13 循环语句(Loops)
- 3.14 冗赘的元素(Lazy Element)
- 3.15 夸夸其谈通用性(Speculative Generality)
- 3.16 临时字段(Temporary Field)
- 3.17 过长的消息链(Message Chains)
- 3.18 中间人(Middle Man)
- 3.19 内幕交易(Insider Trading)
- 3.20 过大的类(Large Class)
- 3.21 异曲同工的类(Alternative Classes with Different Interfaces)
- 3.22 纯数据类(Data Class)
- 3.23 被拒绝的遗赠(Refused Bequest)
- 3.24 注释(Comments)
- 第4章 构筑测试体系
- 4.1 自测试代码的价值
- 4.2 待测试的示例代码
- 4.3 第一个测试
- 4.4 再添加一个测试
- 4.5 修改测试夹具
- 4.6 探测边界条件
- 4.7 测试远不止如此
- 第5章 介绍重构名录
- 5.1 重构的记录格式
- 5.2 挑选重构的依据
- 第6章 第一组重构
- 6.1 提炼函数(Extract Function)
- 6.2 内联函数(Inline Function)
- 6.3 提炼变量(Extract Variable)
- 6.4 内联变量(Inline Variable)
- 6.5 改变函数声明(Change Function Declaration)
- 6.6 封装变量(Encapsulate Variable)
- 6.7 变量改名(Rename Variable)
- 6.8 引入参数对象(Introduce Parameter Object)
- 6.9 函数组合成类(Combine Functions into Class)
- 6.10 函数组合成变换(Combine Functions into Transform)
- 6.11 拆分阶段(Split Phase)
- 第7章 封装
- 7.1 封装记录(Encapsulate Record)
- 7.2 封装集合(Encapsulate Collection)
- 7.3 以对象取代基本类型(Replace Primitive with Object)
- 7.4 以查询取代临时变量(Replace Temp with Query)
- 7.5 提炼类(Extract Class)
- 7.6 内联类(Inline Class)
- 7.7 隐藏委托关系(Hide Delegate)
- 7.8 移除中间人(Remove Middle Man)
- 7.9 替换算法(Substitute Algorithm)
- 第8章 搬移特性
- 8.1 搬移函数(Move Function)
- 8.2 搬移字段(Move Field)
- 8.3 搬移语句到函数(Move Statements into Function)
- 8.4 搬移语句到调用者(Move Statements to Callers)
- 8.5 以函数调用取代内联代码(Replace Inline Code with Function Call)
- 8.6 移动语句(Slide Statements)
- 8.7 拆分循环(Split Loop)
- 8.8 以管道取代循环(Replace Loop with Pipeline)
- 8.9 移除死代码(Remove Dead Code)
- 第9章 重新组织数据
- 9.1 拆分变量(Split Variable)
- 9.2 字段改名(Rename Field)
- 9.3 以查询取代派生变量(Replace Derived Variable with Query)
- 9.4 将引用对象改为值对象(Change Reference to Value)
- 9.5 将值对象改为引用对象(Change Value to Reference)
- 第10章 简化条件逻辑
- 10.1 分解条件表达式(Decompose Conditional)
- 10.2 合并条件表达式(Consolidate Conditional Expression)
- 10.3 以卫语句取代嵌套条件表达式(Replace Nested Conditional with Guard Clauses)
- 10.4 以多态取代条件表达式(Replace Conditional with Polymorphism)
- 10.5 引入特例(Introduce Special Case)
- 10.6 引入断言(Introduce Assertion)
- 第11章 重构API
- 11.1 将查询函数和修改函数分离(Separate Query from Modifier)
- 11.2 函数参数化(Parameterize Function)
- 11.3 移除标记参数(Remove Flag Argument)
- 11.4 保持对象完整(Preserve Whole Object)
- 11.5 以查询取代参数(Replace Parameter with Query)
- 11.6 以参数取代查询(Replace Query with Parameter)
- 11.7 移除设值函数(Remove Setting Method)
- 11.8 以工厂函数取代构造函数(Replace Constructor with Factory Function)
- 11.9 以命令取代函数(Replace Function with Command)
- 11.10 以函数取代命令(Replace Command with Function)
- 第12章 处理继承关系
- 12.1 函数上移(Pull Up Method)
- 12.2 字段上移(Pull Up Field)
- 12.3 构造函数本体上移(Pull Up Constructor Body)
- 12.4 函数下移(Push Down Method)
- 12.5 字段下移(Push Down Field)
- 12.6 以子类取代类型码(Replace Type Code with Subclasses)
- 12.7 移除子类(Remove Subclass)
- 12.8 提炼超类(Extract Superclass)
- 12.9 折叠继承体系(Collapse Hierarchy)
- 12.10 以委托取代子类(Replace Subclass with Delegate)
- 12.11 以委托取代超类(Replace Superclass with Delegate)
- 参考文献
- 重构列表
- 坏味道与重构手法速查表
