在ForumEye的bbs上面看到一篇很理论的讨论,整理后如下:
Composition复合:
在《efficient java》中第14条:复合优先于继承。
代码如下:
public class InstrumentedSet implements Set {
private final Set s;
private int addCount = 0;
.....
public InstrumentedSet(Set s) {
this.s = s;
}
....
// Forwarding methods (转发)
public void clear() { s.clear(); }
public boolean contains(Object o) { return s.contains(0); }
public boolean isEmpty() { return s.isEmpty(); }
public int size() { return s.size(); }
.......
}
delegation代理:
代码:
delegateA {
delegateeB b;
void methodA() { b.methodB(this); }
void do() {}
}
delegateeB {
void methodB(delegateA a) { a.do(); }
}
在现实世界中,假如董事长A把权利授权给总经理B,总经理B一定会获取董事长A才拥有的权利,它会利用这些权利来替公司做事。这才是真正的delegation,也就是说delegatee一定会调用delegate的某些方法,因此你首先得把delegate传递给delegatee。
代理的含义:
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
搂主在What Is Delegation上找到了一些资料:
发表于 @ 2004年07月19日 13:40:00 | 评论( loading... ) | 举报| 收藏