夏天到了

雨季过后,是蘑菇生长的季节

 

delegation(委托)

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》)

posted on 2006-04-06 16:25 蘑菇 阅读(954) 评论(3)  编辑  收藏 所属分类: 开发随感

评论

# re: delegation(委托) 2006-04-06 17:34 蘑菇

加个更容易懂的例子:
delegateA {
delegateeB b;

void methodA() { b.methodB(this); }
void do() {}
}

delegateeB {
void methodB(delegateA a) { a.do(); }
}   回复  更多评论   

# re: delegation(委托) 2006-04-27 15:20 ruidong

能否解释一下上述代码?谢谢蘑菇  回复  更多评论   

# re: delegation(委托) 2006-04-27 19:14 蘑菇

A是委托类,B是被委托类。
A调用B进行委托,委托时A的对象传递给了B.
在B中,使用了A的方法,完成了委托。  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

公告

其实生活很简单

常用链接

留言簿(1)

随笔分类

随笔档案

文章分类

文章档案

相册

搜索

最新评论

阅读排行榜

评论排行榜