责任链模式(Chain of Responsibility Pattern)
情景:假设一个卡牌类游戏,怪物卡和属性卡 可以给怪物增加攻击属性,防御属性
/// <summary> /// 生物基础 /// </summary> public class Creature { public string Name; public int Attack, Defense; public Creature(string name, int attack, int defense) { Name = name; Attack = attack; Defense = defense; } public override string ToString() { return $"Name:{Name},Attack:{Attack},Defense:{Defense}"; } }
创建一个责任链头:
/// <summary> /// 装备卡 /// </summary> public class CreatureModifer { protected Creature creature; protected CreatureModifer next; public CreatureModifer(Creature creature) { this.creature = creature; } public void Add(CreatureModifer cm) { if (next != null) next.Add(cm); else next = cm; } public virtual void Handle() => next?.Handle(); }
双倍攻击:
/// <summary> /// 双重攻击Buff /// </summary> public class DoubleAttackBuff : CreatureModifer { public DoubleAttackBuff(Creature creature) : base(creature) { } public override void Handle() { Console.WriteLine("获取Buff,双倍攻击!"); creature.Attack *= 2; base.Handle(); } }
增加防御:
public class IncreaseProtectionBuff : CreatureModifer { public IncreaseProtectionBuff(Creature creature) : base(creature) { } public override void Handle() { Console.WriteLine("获取Buff,防御+5!"); creature.Defense += 5; base.Handle(); } }
禁止BUFF:
public class BuufProhibition : CreatureModifer { public BuufProhibition(Creature creature) : base(creature) { } public override void Handle() { //base.Handle(); } }
开始使用:
var Goblin = new Creature("Goblin", 2, 2);//创建一个哥布林 Console.WriteLine(Goblin); var buff = new CreatureModifer(Goblin);//创建一个责任链头 //buff.Add(new BuufProhibition(Goblin));//Buff无效 buff.Add(new DoubleAttackBuff(Goblin));//增加双倍攻击 buff.Add(new IncreaseProtectionBuff(Goblin));//增加防御力 buff.Handle();//Buff生效 Console.WriteLine(Goblin);
来看结果: