How to use the Strategy Pattern with C#?

前端 未结 7 757
暗喜
暗喜 2021-01-01 18:29

Here\'s what I have so far:

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

namespace Strategy
{
    class Knife          


        
相关标签:
7条回答
  • 2021-01-01 19:14

    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.

    0 讨论(0)
提交回复
热议问题