麻烦一个简单的策略模式示例

时间:2011-02-03 03:14:44

标签: c# design-patterns strategy-pattern

错误是:

  

FirstPattern.Character.Character'确实如此   不包含取0的构造函数   参数

以下是代码:

public interface WeaponBehavior
{
    void UseWeapon();
}

class SwordBehavior : WeaponBehavior
{
    public void UseWeapon()
    {
        Console.WriteLine("A sword as plain as your wife.");
    }
}

然后,我有一个角色类:

public abstract class Character
{
    WeaponBehavior weapon;

    public Character(WeaponBehavior wb)
    {
        weapon = wb;
    }

    public void SetWeapon(WeaponBehavior wb)
    {
        weapon = wb;
    }

    public abstract void Fight();
}



public class Queen : Character
{        
    public Queen(WeaponBehavior wb)
    {
        SetWeapon(wb);
    }

    public override void Fight()
    {

    }
}

我不确定我应该对字符类和子类做什么。你们能帮我们朝正确的方向推进吗?

1 个答案:

答案 0 :(得分:1)

由于Queen派生自CharacterCharacter只有一个带WeaponBehavior参数的构造函数,因此您需要在Queen中显式调用基础构造函数构造函数 - 这意味着你在那里调用SetWeapon也是不必要的:

public Queen(WeaponBehavior wb) : base(wb)
{
}

或者,您可以在Character中提供默认构造函数,并保持原始代码不变:

public abstract class Character
{
   WeaponBehavior weapon;

   public Character() { }
   ...