.NET Delegates: A C# Bedtime Story

Tight Coupling

Once upon a time, in a strange land south of here, there was a worker named Peter. He was a diligent worker who would readily accept requests from his boss. However, his boss was a mean, untrusting man who insisted on steady progress reports. Since Peter did not want his boss standing in his office looking over his shoulder, Peter promised to notify his boss whenever his work progressed. Peter implemented this promise by periodically calling his boss back via a typed reference like so:

紧耦合

从前,在南方有一块神奇的土地,有一个叫做Peter的工人。他是个勤劳员工,从来不拒绝老板的任何要求。可是他的老板却是个不相信别人的吝啬鬼,为了防止工人偷懒,他坚持要随时知道他们的工作进展。可是Peter却不喜欢老板监视自己的工作。于是Peter向老板保证,一旦工作有任何进展,都会向他报告。于是Peter通过引用一个类[老板],根据工作的进展回调老板[的方法],来实现自己的承诺。

 

class  Worker  {
    
public void Advise(Boss boss) { _boss = boss; }
    
public void DoWork() {
        Console.WriteLine(
"Worker: work started");
        
if( _boss != null ) _boss.WorkStarted();

        Console.WriteLine(
"Worker: work progressing");
        
if( _boss != null ) _boss.WorkProgressing();

        Console.WriteLine(
"Worker: work completed");
        
if( _boss != null ) {
            
int grade = _boss.WorkCompleted();
            Console.WriteLine(
"Worker grade= " + grade);
        }

    }

    
private Boss _boss;
}


class  Boss  {
    
public void WorkStarted() /**//* boss doesn't care. */ }
    
public void WorkProgressing() /**//* boss doesn't care. */ }
    
public int WorkCompleted() {
        Console.WriteLine(
"It's about time!");
        
return 2/**//* out of 10 */
    }

}


class  Universe  {
    
static void Main() {
        Worker  peter 
= new Worker();
        Boss        boss 
= new Boss();
        peter.Advise(boss);
        peter.DoWork();

        Console.WriteLine(
"Main: worker completed work");
        Console.ReadLine();
    }

}
Interfaces

Now Peter was a special person. Not only was he able to put up with his mean-spirited boss, but he also had a deep connection with the universe around him. So much so that he felt that the universe was interested in his progress. Unfortunately, there was no way for Peter to advise the Universe of his progress unless he added a special Advise method and special callbacks just for the Universe, in addition to keeping his boss informed. What Peter really wanted to do was to separate the list of potential notifications from the implementation of those notification methods. And so he decided to split the methods into an interface:


接口

现在,Peter只是一个特别的人,他不仅要忍受他那吝啬的老板,还与其周围的宇宙有着紧密的联系。所以他想,可能宇宙也想知道我的工件进展。他怎么才能在保持与老板通信的同时,还能向宇宙报告他的工作进度呢?如果按照原来的想法,他唯一的办法就是:必须专门地添加一个Advise()方法以实现对Universe类的引用,并回调它的方法。于是Peter想到,把所有可能的通知方法从具体的实现中分离出来,作为一个接口[,让老板(BOSS)和宇宙(Universe)来实现,这样他就不用管他通知的是哪一类了]。

 

interface  IWorkerEvents  {
void WorkStarted();
void WorkProgressing();
int WorkCompleted();
}
class Worker {
public void Advise(IWorkerEvents events) { _events = events; }
public void DoWork() {
Console.WriteLine(
"Worker: work started");
if( _events != null ) _events.WorkStarted();
Console.WriteLine(
"Worker: work progressing");
if(_events != null ) _events.WorkProgressing();
Console.WriteLine(
"Worker: work completed");
if(_events != null ) {
int grade = _events.WorkCompleted();
Console.WriteLine(
"Worker grade= " + grade);
}

}

private IWorkerEvents _events;
}

class Boss : IWorkerEvents {
public void WorkStarted() /* boss doesn't care. */ }
public void WorkProgressing() /* boss doesn't care. */ }
public int WorkCompleted() {
Console.WriteLine(
"It's about time!");
return 3/* out of 10 */
}

}

Delegates

Unfortunately, Peter was so busy talking his boss into implementing this interface that he didn't get around to notifying the Universe, but he knew he would soon. At least he'd abstracted the reference of his boss far away from him so that others who implemented the IWorkerEvents interface could be notified of his work progress.

Still, his boss complained bitterly. "Peter!" his boss fumed. "Why are you bothering to notify me when you start your work or when your work is progressing?!? I don't care about those events. Not only do you force me to implement those methods, but you're wasting valuable work time waiting for me to return from the event, which is further expanded when I am far away! Can't you figure out a way to stop bothering me?"

And so, Peter decided that while interfaces were useful for many things, when it came to events, their granularity was not fine enough. He wished to be able to notify interested parties only of the events that matched their hearts' desires. So, he decided to break the methods out of the interface into separate delegate functions, each of which acted like a little tiny interface of one method each:

delegate void WorkStarted();
delegate void WorkProgressing();
delegate int WorkCompleted();
委托

 

不幸的是,当Peter忙于说服彵的老板去实现接口以至于他抽不出身来去通知宇宙,但是他知道不久也是要去的。至少,当老板远离时,他可以转移对老板的引用[即改变_events ——译者注],这样的话,其它实现了IWorkerEvents接口的人也能得到他的工作进程。
可是,他的老板还是不满意。“Peter!”他抱怨道,“为什么每次你开始工作时和工作过程中都要来烦我?!?我不关心这些。你却强迫我实现这些方法,不仅如此,你还在浪费宝贵的时间来等待我的答复,当我远离时,你浪费的时间会更多!你能不能想一个办法,不要老是来打挠我?”
这时,Peter意识到,接口在很多情况下很有用,可是在处理事件时,它还是不够灵活。他希望能够根据别人的需要,只通知他们感兴趣的那一部分事件。于是他决定将接口分离为一个个的委托——就像是一个极小的只包含一个方法的接口。
 
 
class  Worker  {
public void DoWork() {
Console.WriteLine(
"Worker: work started");
if( started != null ) started();
Console.WriteLine(
"Worker: work progressing");
if( progressing != null ) progressing();
Console.WriteLine(
"Worker: work completed");
if( completed != null ) {
int grade = completed();
Console.WriteLine(
"Worker grade= " + grade);
}

}

public WorkStarted started;
public WorkProgressing progressing;
public WorkCompleted completed;
}

class  Boss  {
public int WorkCompleted() {
Console.WriteLine(
"Better");
return 4/**//* out of 10 */
}

}

class  Universe  {
static void Main() {
Worker  peter 
= new Worker();
Boss        boss 
= new Boss();
peter.completed 
= new WorkCompleted(boss.WorkCompleted);
peter.DoWork();
Console.WriteLine(
"Main: worker completed work");
Console.ReadLine();
}

}


Static Listeners

This accomplished the goal of not bothering his boss with events that he didn't want, but still Peter had not managed to get the universe on his list of listeners. Since the universe is an all-compassing entity, it didn't seem right to hook delegates to instance members (imagine how many resources multiple instances of the universe would need...). Instead, Peter need to hook delegates to static members, which delegates support fully:

静态监听者

这样,他虽然实现了不再拿老板不关心的事件去烦他的目的,可是他还是没能把宇宙它加到他的监听者列表中去。因为宇宙是一个包含一切的实体,似乎不适于把它实例化后挂钩到委托[即委托对方法的引用——译者注](想象一下,实例化上一个宇宙将需要多少资源)。事实上,Peter需要将委托挂钩到静态成员:

class  Universe  {    
static void WorkerStartedWork() {
        Console.WriteLine(
"Universe notices worker starting work");   
 }


 
static int WorkerCompletedWork() {
        Console.WriteLine(
"Universe pleased with worker's work"); 
        
return 7;   
 }


static void Main() {
        Worker  peter 
= new Worker();
        Boss        boss 
= new Boss();
        peter.completed 
= new WorkCompleted(boss.WorkCompleted);
        peter.started 
= new WorkStarted(Universe.WorkerStartedWork);
        peter.completed 
= new WorkCompleted(Universe.WorkerCompletedWork);
        peter.DoWork();
        Console.WriteLine(
"Main: worker completed work");
        Console.ReadLine();
}

}

 

Events

Unfortunately, the Universe being very busy and unaccustomed to paying attention to individuals, has managed to replace Peter's boss's delegate with its own. This is an unintended side effect of making the delegate fields public in Peter's Worker class. Likewise, if Peter's boss gets impatient, he can decide to fire Peter's delegates himself (which is just the kind of rude thing that Peter's boss was apt to do):

        // Peter's boss taking matters into his own hands
if( peter.completed != null ) peter.completed();

Peter wants to make sure that neither of these can happens. He realizes he needs to add registration and unregistration functions for each delegate so that listeners can add or remove themselves, but can't clear the entire list or fire Peter's events. Instead of implementing these functions himself, Peter uses the event keyword to make the C# compiler build these methods for him:

事件

不幸的是,宇宙很忙,也不习惯去注意细节,把peter.completed委托对boss.WorkCompleted的引用替换成了对自己方法的引用。这是把Worker类的委托域作为公有[public]的一个(并因为不作任何限定而造成的)无意识的不良影响。同样(因为这),如果Peter的老板没有耐性了,他也可以决定亲自来引发Peter的委托(这也是Peter的老板惯于做的粗鲁的事)

//  Peter's boss taking matters into his own hands 

 
if ( peter.completed  !=   null  ) peter.completed();

Peter想确保这些都不要发生。他意识到,他需要为每个委托添加注册和注销[对方法的引用]的方法,这样的话监听者可以自行添加或是移除监听了,但是不能清空整个监听者列表或自己来引发Peter的事件。Peter使用了关键字event让C#编译器为他构建而不是自己亲自去实现这现方法:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值