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


 



你可能感兴趣的:(delegation(委托) vs. composition(复合) ?)