Lets also try to say what delegation is NOT.
From my above theory, a simple subroutine may have responsibility for the computation of some part of a program, but a subroutine call is not delegation because it is direct. It lacks a layer of indirection. A function-pointer IS however, since it can point to any function, and the decision of what function it points to must already have been made when it is dereferenced and called. Even a switch/case statement can be delegation, provided it adds a layer of indirection.
So what does OO and polymorphic behavior have to do with delegation, if delegation is such a simple, ubiquitous thing? Perhaps this is the real core of the matter. OO is about resolving polymorphic behavior by delegating to objects.
[/list:o]
按照上面的定义,在delegate和delegatee之间必须有一层indirection。画个简单的示意图:
代码
- 1:
- A --> B
- 2:
- delegate -----> delegatee
- ^ |
- | indirection |
- --------------------
代码
- part1
- delegateA {
- delegateeB b;
- void methodA() { b.methodB();}
- }
- delegateeB {
- void methodB() {}
- }
上面的代码就不是delegation,而是composition,因为直接调用了delegatee的方法,这只是forwarding methods。
代码
- part2
- delegateA {
- delegateeB b;
- void methodA() { b.methodB(this); }
- void do() {}
- }
- delegateeB {
- void methodB(delegateA a) { a.do(); }
- }
part2好像又回到了part1,其实不然,delegate已经把自身pass给了delegatee,并且delegatee调用了delegate的方法,这就是一种indirection。
在现实世界中,假如董事长A把权利授权给总经理B,总经理B一定会获取董事长A才拥有的权利,它会利用这些权利来替公司做事。这才是真正的delegation,也就是说delegatee一定会调用delegate的某些方法,因此你首先得把delegate传递给delegatee。