delegation(委托) vs. composition(复合) ?

在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上找到了一些资料:

  1. Let me state a theory: polymorphic behavior is always delegation of some sort, and thus delegation (to impliment polymorphism) always has a layer of indirection. Please find a problem here, so we can make this more succinct/correct, or dis/prove it.

    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.

  2. Better yet: delegation is done by the caller, while indirection is a function of (dispatch to) the callee


 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值