Delegation VS. InheritanceInheritance:
the relationship between superclass and subclass cannot be changed during runtime.
modify superclass also changing subclass
IS-A relationDelegation:
One object forwards method call to another object, which is called delegate. 
delegate can be changed at runtime, by changing the reference of delegate.
USE relation 
java AWT1.0 is based on inheritance, now use Delegation Event Model. A very simple example:interface I{}
class A implements I{}
class B implements I{}class client {
   void f(I i){ //delegation, i can be changed
   i.method();    }
}

解决方案 »

  1.   

    More accurate example:interface I{ void f();}
    class A implements I{void f(){....}}
    class B implements I{void f(){....}}class Client implements I{
       I delegate;
       /*  not important
       public Client(){
           delegate=new A();// default
       }
       */
       static setI(I i){ 
           delegate=i ;
       }
       void f(){ 
       ...
         delegate.f(); 
       ...
       }
    }public class Test{
        public static void main(Strin[] args){
             Client c=new Client;
             c.set(new A());
             c.f();
             c.set(new B());
             c.f();
        }
    }
      

  2.   

    上面例子不是多态吗?Delegation Event Model像awt的事件监听处理模型自身事件委托给监听器去执行。
      

  3.   

    看看 《Design patten》 (《设计模式》),就知道了
      

  4.   

    委托是设计组件的时候,最常用的设计模式我们经常说的第三方插件技术,就是一种运行期的委托。继承和委托,是不同时期的软件复用技术,继承,仅仅是编译期,也就是源代码级的复用,也就是说,当你的类继承了一个累以后,在运行期,这个就不可改变了。而委托呢,是运行期的软件复用技术。大家对windows系统的拖拽功能都很熟悉,这就是一种委托技术。dcom组件,也是一种委托技术。。
      

  5.   

    强,果然高手。友情Up
    将“流氓无赖”测试到底
    ——始于2003年7月
    树欲止而风不停,行云流水匆匆去;
    树梢蚂蚱凭空望,江边浪花碎巨石; 支持“流金岁月”!!!
    发送框,少个“右键菜单,选择粘贴”;
    ——2003年12月24日am^@^
      

  6.   

    简单的说,如果你要复用一个模块A中的功能,java中可以继承A实现,也可以在一个新的类B中维护一个A的实例或引用,B在需要复用A的功能是,调用A实现,如此就是delegate。
      

  7.   

    C#在语法上支持delegate,Microsoft还是很牛的,只是我不喜欢:)
      

  8.   

    simonhappy() 兄说的,叫做聚合,不叫做委托。。在逻辑上叫做关联不叫做依赖。
      

  9.   

    请大家手头常备 Effective Java 一书.
    本次话题请参阅 Chapter 4: Item 14: Favor composition over inheritance.simonhappy()所说的,A于B之间确实是关联的关系,但是也是delegation的关系.
      

  10.   

    to xiaohaiz(老土进城,两眼通红) :
    Effective Java前天刚买的啊,哈哈,还没看,赶快看看去楼