如何在C#中使用策略模式?

Ser*_*pia 16 c# strategy-pattern

这是我到目前为止所拥有的:

namespace Strategy
{
    interface IWeaponBehavior
    {
        void UseWeapon();
    }
}

namespace Strategy
{
    class Knife : IWeaponBehavior
    {
        public void UseWeapon()
        {
            Console.WriteLine("You used the knife to slash the enemy! SLASH SLASH!");
        }
    }
}

namespace Strategy
{
    class Pan : IWeaponBehavior
    {
        public void UseWeapon()
        {
            Console.WriteLine("You use the pan! 100% Adamantium power! BONG!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我有一个Character.cs超类.该超类如何实现武器行为,以便子类可以更具体.

namespace Strategy
{
    class Character
    {
        public IWeaponBehavior weapon;

        public Character(IWeaponBehavior specificWeapon)
        {
            weapon = specificWeapon;
        }        
    }
}

namespace Strategy
{
    class Thief : Character
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我该如何实现呢?我对实际代码需要的内容非常困惑.

我知道这可能要求太多,但是如果你能写出实际的代码以便我可以研究它,那对你们来说这将是非常好的.我通过看代码来学习.:P很多人都可以从这个问题中受益.

Gro*_*ozz 26

在课堂上使用依赖注入Character

public class Character
{
    public Character(IWeaponBehavior weapon) 
    {
        this.weapon = weapon;
    }

    public void Attack()
    {
        weapon.UseWeapon();
    }

    IWeaponBehavior weapon;
}

public class Princess: Character
{
    public Princess() : base(new Pan()) { }
}

public class Thief: Character
{
    public Thief() : base(new Knife()) { }
}

...

Princess p = new Princess();
Thief t = new Thief();

p.Attack(); // pan
t.Attack(); // knife
Run Code Online (Sandbox Code Playgroud)

按要求编辑.

  • @Joshua - 但是你假设所有公主都会使用Pan,如果你有一个喜欢使用刀子的邪恶公主怎么办... (3认同)

cwa*_*wap 5

有几种可能性.你真正要问的是,"特定角色应该如何知道使用哪种武器?".

你可以有一个角色工厂,可以创建并向角色注入正确类型的武器(这听起来是错误的:)),或者让特定角色的构造者负责创建武器.


mar*_*r75 0

这是一篇关于在 C# 中使用此模式的非常集中的文章:http://www.lowendahl.net/showShout.aspx ?id=115