策略模式——定义了算法族,分别分装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。(摘自《Head First Design Patterns》) 以下是自已用VS画了一个简图: ![]()
![]()
武器接口:
武器接口:
/// <summary>
/// 武器接口
/// </summary>
public interface IWeapon
{
/// <summary>
/// 武器攻击
/// </summary>
void UseWeapon();
}
实现的4个武器:
public class Axe : IWeapon
{
#region IWeapon 成员
/// <summary>
/// 斧头砍劈
/// </summary>
public void UseWeapon()
{
Console.WriteLine("斧头砍劈");
}
#endregion
}
public class Knife : IWeapon
{
#region IWeapon 成员
/// <summary>
/// 实现匕首刺杀
/// </summary>
/// <remarks></remarks>
public void UseWeapon()
{
Console.WriteLine("匕首刺杀");
}
#endregion
}
public class BowAndArrow : IWeapon
{
#region IWeapon 成员
/// <remarks>弓箭射击</remarks>
public void UseWeapon()
{
Console.WriteLine("弓箭射击");
}
#endregion
}
public class NoWeapon : IWeapon
{
#region IWeapon 成员
/// <summary>
/// 没有武器
/// </summary>
public void UseWeapon()
{
Console.WriteLine("没有武器");
}
#endregion
}
接下来是人的抽象类:
public abstract class BasePerson
{
private IWeapon _weapon;
public IWeapon Weapon
{
get
{
return _weapon;
}
set
{
_weapon = value;
}
}
public void SetWeapon(IWeapon w)
{
this._weapon = w;
}
public abstract void Fight();
public void UseWeapon()
{
this.Weapon.UseWeapon();
}
}
然后实现一个陆军一个海军使用武器(一时没想出什么好的名称,就随便拿海军陆军充当了):
public class Army : BasePerson
{
public Army()
{
this.SetWeapon(new NoWeapon());
}
public override void Fight()
{
Console.Write("Army ");
UseWeapon();
}
}
public class Navy : BasePerson
{
public Navy()
{
this.SetWeapon(new NoWeapon());
}
public override void Fight()
{
Console.Write("Navy ");
UseWeapon();
}
}
现在来看看调用,每个人都可以换武器攻击以产生不同的效果,就实现了策略模式的思想:
Army army = new Army();
army.Fight();
army.SetWeapon(new Knife());
army.Fight();
army.SetWeapon(new Axe());
army.Fight();
Navy navy = new Navy();
navy.Fight();
navy.SetWeapon(new BowAndArrow());
navy.Fight();
输出结果:
Army 没有武器
Army 匕首刺杀
Army 斧头砍劈
Navy 没有武器
Navy 弓箭射击
没有怎么写过BLOG,看看自己的空空的,就随手写了一些,还忘大家不要见笑。
1594

被折叠的 条评论
为什么被折叠?



