How to use the Strategy Pattern with C#?

前端 未结 7 783
暗喜
暗喜 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

    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.

提交回复
热议问题