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

发布于 2024-09-14 02:02:12 字数 1024 浏览 3 评论 0原文

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

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!");
        }
    }
}

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

namespace Strategy
{
    class Character
    {
        public IWeaponBehavior weapon;

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

namespace Strategy
{
    class Thief : Character
    {

    }
}

我怎样才能实现这个?我对实际代码需要什么感到非常困惑。

我知道这可能要求太多,但是如果您可以编写实际的代码以便我可以研究它,那就太好了。我通过看代码来学习。 :P 许多人可以从这个问题中受益。

Here's what I have so far:

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!");
        }
    }
}

Now if I have a Character.cs superclass. how can that superclass implement a weaponbehavior so that children classes can be more specific.

namespace Strategy
{
    class Character
    {
        public IWeaponBehavior weapon;

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

namespace Strategy
{
    class Thief : Character
    {

    }
}

How can I implement this? I'm very confused on what the actual code needs to be.

I know this might be asking too much, but if you could write the actual code so I could study it, that would be very nice of you guys. I learn by seeing code. :P Many people could benefit from this question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

表情可笑 2024-09-21 02:02:12

在类 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

按要求编辑。

Use dependency injection in class 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

Edited as requested.

留蓝 2024-09-21 02:02:12

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

您可以拥有一个角色工厂来创建并将正确类型的武器注入到角色中(这听起来是错误的:)),或者让特定角色的构造函数负责创建武器。

There's a few possibilities. What you're really asking is, "how should a specific character know which weapon to use?".

You could either have a Character factory that would create and inject the right type of weapon into the character (That sounded wrong :) ), or let the constructor of a specific character take care of creating the weapon.

月亮邮递员 2024-09-21 02:02:12
  class Character
  {
    private IWeaponBehavior _weapon;

    // Constructor
    public Character(IWeaponBehavior strategy)
    {
      this._weapon = strategy;
    }

    public void WeaponInterface()
    {
      _weapon.UseWeapon();
    }
  }
  class Character
  {
    private IWeaponBehavior _weapon;

    // Constructor
    public Character(IWeaponBehavior strategy)
    {
      this._weapon = strategy;
    }

    public void WeaponInterface()
    {
      _weapon.UseWeapon();
    }
  }
染柒℉ 2024-09-21 02:02:12
public class Character
{
    IWeaponBehavior Weapon;
}

public class Princess : Character
{
    Weapon = new Pan();
}

public class Thief : Character
{
    Weapon = new Knife();
}
public class Character
{
    IWeaponBehavior Weapon;
}

public class Princess : Character
{
    Weapon = new Pan();
}

public class Thief : Character
{
    Weapon = new Knife();
}
有深☉意 2024-09-21 02:02:12

看一下依赖注入和依赖注入然后还要研究控制反转。

TekPub 有一个关于这两个想法的精彩免费剧集,使用与您的示例非常相似的示例。这应该可以帮助您获得具体的示例。 :-)

http://tekpub.com/view/concepts/1

视频中的示例代码:

class Samurai {
  IWeapon _weapon;

  public Samurai() {
   _weapon = new Sword();
  }

  public Samurai(IWeapon weapon) {
   _weapon = weapon;
  }

  public void Attack(string target) {
    _weapon.Hit(target);
  }
}

上面是DI(带有IWeapon构造函数)。现在添加控制反转,您可以获得更多控制权。

使用 IOC 容器,您将能够通过注入而不是在类本身中控制 IWeapon。

该视频使用 NInject 作为 IOC,并展示了如何消除 IWeapon 构造函数并获得对类和所有类的控制需要使用 IWeapon 在一个位置/配置区域中使用您想要的东西。

视频示例:

class WarriorModule: NinjectModule {
  public override void Load() {
   Bind<IWarrior>().To<Samurai>();
   Bind<IWeapon>().To<Sword>();
}

上面的配置告诉 NInject,每当它遇到 IWarrior 使用 Samurai 以及每当它鼓励 IWeapon 使用 Sword 时。

该视频接着解释了这个小小的改变如何提高您的灵活性。它为使用远程武器等的萨穆里亚人添加了另一个模块......

您可以根据需要/想要更改这些。

Take a look at dependency injection & then also look into Inversion of Control.

TekPub has a great free episode on these two ideas using a sample very similar to yours. This should help you with a concrete sample. :-)

http://tekpub.com/view/concepts/1

Sample code from video:

class Samurai {
  IWeapon _weapon;

  public Samurai() {
   _weapon = new Sword();
  }

  public Samurai(IWeapon weapon) {
   _weapon = weapon;
  }

  public void Attack(string target) {
    _weapon.Hit(target);
  }
}

The above is DI (with IWeapon constructor). Now adding Inversion of Control you gain even more control.

Using an IOC container you will be able to control the IWeapon via injection instead of in the class itself.

The video uses NInject as it's IOC and shows how you can eliminate the IWeapon Constructor and gain control over the class and all classes needing to use IWeapon to use what you want in one location/configuration area.

Sample from video:

class WarriorModule: NinjectModule {
  public override void Load() {
   Bind<IWarrior>().To<Samurai>();
   Bind<IWeapon>().To<Sword>();
}

The above configuration tells NInject that whenever it encounters an IWarrior to use Samurai and whenever it encourters an IWeapon to use Sword.

The video goes on to explain how this little change increases your flexibility. It adds another Module for a Samuria who uses a ranged weapon, etc....

You can change these as needed/wanted.

ˇ宁静的妩媚 2024-09-21 02:02:12

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

Here's a very focused article on using this pattern in C#: http://www.lowendahl.net/showShout.aspx?id=115

征棹 2024-09-21 02:02:12

如果你的角色都有自己的特定武器,那么你实际上不需要使用策略模式。您可以使用简单的多态性。但无论如何,战略模式可能会更加清晰。

您只需要初始化武器:

public class Character
{
     IWeapenBehavior weapon;

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


public class Thief : Character
{
      Thief()
      {
           weapon = new Knife();
      }
}

在控制角色的代码中,您可以调用 Attack() 方法。

If your characters all have their own specific weapon, you don't actually need to use the strategy pattern. You could use plain polymorphism. But the strategy pattern could be cleaner anyway.

You just need to intitialize the weapon:

public class Character
{
     IWeapenBehavior weapon;

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


public class Thief : Character
{
      Thief()
      {
           weapon = new Knife();
      }
}

In the code that controls your Characters, you can call the Attack() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文