Delegation 定义:
Delegation is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. But with inheritance, an inherited operation can always refer to the receiving object through the this member variable in C++ and self in Smalltalk. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver
我的理解:
A 把外界传来的讯息" 转送" 给B ﹐由B 处理之﹐我们称A 委托B 。当一些事物互相沟通分工合作时常用妥托观念。
值得注意的是:
delegate -----> delegatee
^ |
| indirection |
--------------------
delegate将自己(对象)传给delegatee,使delegatee可以通过该对象执行那些委托的操作。
举个例子:
在某个框架的组成部分中,对窗口设计,可以支持任意形状的窗口。
开始的时候考虑是不是使用子类来实现,乍一看似乎是比较好的,但是考虑到对窗口来说形状只能是它的一项属性:窗口不是一“种”形状——窗口“有”形状。(引自《The Pragmatic Programmer》)所以采用委托的方式。
这时,我们定义一个被委托(delegatee)类Shape和一个委托(delegate)类window。
public abstract class Shape{
//....
public abstract boolean overlaps(Shape s);
public abstract int getArea();
}
public class window{
private Shape shape;
public window(Shape shape){
this.shape = shape;
...
}
public void setShape(Shape shape){
this.shape = shape;
...
}
public boolean overlaps(window w){
return shape.overlaps(w);
}
public int getArea(){
return shape.getArea();
}
}
class引自《The Pragmatic Programmer》)