踢球时想到的装饰器模式

王朝学院·作者佚名  2016-05-20
窄屏简体版  字體: 小  |  中  |  大  |  超大  

踢球时想到的装饰器模式最近踢了场球,9人制比赛,上半场我们采用防守阵型效果不佳,下半场采用进攻阵型取得了比赛的主动。我们上下半场所采取的策略,似乎可以用"装饰器"模式实现一遍。

首先肯定是抽象基类。

public abstract class OurStrategy

{

public abstract void Play(string msg);

}

通常,在上半场,我们一般都使用防守阵型。

public class OurDefaultStategy : OurStrategy

{

public override void Play(string msg)

{

Console.WriteLine("上半场4-1-2-1防守阵型");

}

}

下半场,会根据上半场的态势而调整阵型。也就是需要实现OurStrategy这个抽象类。不过,先不急,我们还得先抽象出一个实现OurStrategy这个抽象类、充当装饰器的一个抽象类。

public abstract class OurDecorator : OurStrategy

{

PRivate OurStrategy _ourStrategy;

public OurDecorator(OurStrategy ourStrategy)

{

this._ourStrategy = ourStrategy;

}

public override void Play(string msg)

{

if (_ourStrategy != null)

{

_ourStrategy.Play(msg);

}

}

}

以上,这个充当装饰器的抽象类,接收某个实现OurStrategy抽象基类的子类实例,并执行OurStrategy抽象基类的方法Play。

接下来,实现OurDecorator这个充当装饰器的类。

public class AttackStategy : OurDecorator

{

public AttackStategy(OurStrategy ourStrategy) : base(ourStrategy)

{

}

public override void Play(string msg)

{

base.Play(msg);

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航