学习策略模式的时候看到这篇文章感觉不错,这里记录下,作者使用了角色的技能来讲解,其实在游戏里面,我想这种应该是用枚举来实现的,一个骑士可以用任何武器,灵活的应用吧,可能他这里是为了讲解策略模式。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JackYong.Strategy.Solution
{
public enum UserSkill
{
Sword,
Axe,
Nothing,
Weapon
}
}
策略模式代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace JackYong.Strategy.Solution
{
#region 封装 UseWeapon() 行为
// 定义使用 武器接口
public interface IWeaponable
{
void UseWeapon();
}
// 使用 剑 的类
public class UseSword : IWeaponable
{
public void UseWeapon()
{
Console.WriteLine("Action: Sword Armed. There is a sharp sword in my hands now.");
}
}
// 使用 斧 的类
public class UseAxe : IWeaponable
{
public void UseWeapon()
{
Console.WriteLine("Action: Axe Armed. There is a heavy axe in my hands now.");
}
}
// 不能使用武器的类
public class UseNothing : IWeaponable
{
public void UseWeapon()
{
Console.WriteLine("Speak: I can't use any weapon.");
}
}
#endregion
#region 定义角色类
// 角色基类
public abstract class Character
{
protected IWeaponable WeaponBehavior; // 通过此接口调用实际的 UseWeapon方法。
// 使用武器,通过接口来调用方法
public void UseWeapon()
{
WeaponBehavior.UseWeapon();
}
// 动态地给角色更换武器
public void ChangeWeapon(IWeaponable newWeapon)
{
Console.WriteLine("Haha, I've got a new equip.");
WeaponBehavior = newWeapon;
}
public void Walk()
{
Console.WriteLine("I'm start to walk ...");
}
public void Stop()
{
Console.WriteLine("I'm stopped.");
}
public abstract void DisplayInfo(); // 显示角色信息
}
// 定义野蛮人
public class Barbarian : Character
{
public Barbarian()
{
// 初始化继承自基类的WeaponBehavior变量
WeaponBehavior = new UseAxe(); // 野蛮人用斧
}
public override void DisplayInfo()
{
Console.WriteLine("Display: I'm a Barbarian from northeast.");
}
}
// 定义圣骑士
public class Paladin : Character
{
public Paladin()
{
WeaponBehavior = new UseSword();
}
public override void DisplayInfo()
{
Console.WriteLine("Display: I'm a paladin ready to sacrifice.");
}
}
// 定义法师
public class Wizard : Character
{
public Wizard()
{
WeaponBehavior = new UseNothing();
}
public override void DisplayInfo()
{
Console.WriteLine("Display: I'm a Wizard using powerful magic.");
}
}
#endregion
// 测试程序
class Program
{
static void Main(string[] args)
{
Character barbarian = new Barbarian(); // 默认情况下野蛮人用斧
barbarian.DisplayInfo();
barbarian.Walk();
barbarian.Stop();
barbarian.UseWeapon();
barbarian.ChangeWeapon(new UseSword()); // 现在也可以使用剑
barbarian.UseWeapon();
barbarian.ChangeWeapon(new UseNothing());// 也可以让他什么都用不了,当然一不会这样:)
barbarian.UseWeapon();
}
}
}