

static void Main(string[] args)
{
FootballMatch match = new FootballMatch();
Audience justin = new Audience("justin");
Audience terry = new Audience("terry");
match.Observers.Add(justin);
match.Observers.Add(terry);
match.Play();
}
{
FootballMatch match = new FootballMatch();
Audience justin = new Audience("justin");
Audience terry = new Audience("terry");
match.Observers.Add(justin);
match.Observers.Add(terry);
match.Play();
}
足球比赛中可能不只球员,还有天气,裁判等各要素,需要让足球比赛和它的观察者们偶合度更小,我们尝试着用委托和事件来重构它.

static void Main(string[] args)
{
FootballMatch match = new FootballMatch();
Audience justin = new Audience("justin");
Audience terry = new Audience("terry");
match.BeforeMatch += new MatchHandler(match_BeforeMatch);
match.BeforeMatch +=new MatchHandler(justin.Excited);
match.BeforeMatch +=new MatchHandler(terry.nervous);
match.AfterMatch +=new MatchHandlerEnd(justin.KnowResult);
match.AfterMatch +=new MatchHandlerEnd(terry.KnowResult);
match.AfterMatch += new MatchHandlerEnd(match_AfterMatch);
match.Play();
}
static void match_AfterMatch(bool isWin)
{
if (isWin)
{
Console.WriteLine("Snow
..");
}
else
{
Console.WriteLine("Rain
..");
}
}
static void match_BeforeMatch()
{
Console.WriteLine("wind
.");
}
通过带参数的委托可以实现中国队赢球或输球后不同的结果.{
FootballMatch match = new FootballMatch();
Audience justin = new Audience("justin");
Audience terry = new Audience("terry");
match.BeforeMatch += new MatchHandler(match_BeforeMatch);
match.BeforeMatch +=new MatchHandler(justin.Excited);
match.BeforeMatch +=new MatchHandler(terry.nervous);
match.AfterMatch +=new MatchHandlerEnd(justin.KnowResult);
match.AfterMatch +=new MatchHandlerEnd(terry.KnowResult);
match.AfterMatch += new MatchHandlerEnd(match_AfterMatch);
match.Play();
}
static void match_AfterMatch(bool isWin)
{
if (isWin)
{
Console.WriteLine("Snow


}
else
{
Console.WriteLine("Rain


}
}
static void match_BeforeMatch()
{
Console.WriteLine("wind


}

当中国队输球了,愤怒的观众把电视机砸了,天空也开始下雨了.
你也可以任意添加观察者到这场足球比赛里,只要符合所定义委托的规定就行.
僵化的代码需要重构,落后的中国足球体制是不是也需要重构呢?