一張圖讀懂阿里雲資料庫架構與選型
阿新 • • 發佈:2022-05-19
延續責任鏈模式:
https://www.cnblogs.com/Zingu/p/16309483.html
以上例子是增加永久防禦和攻擊,假設增加增益屬性只在一個回合內或者一段時間內有效該如何處理?
增加一個遊戲管理者:用來查詢各項屬性。
public class Game { public event EventHandler<Query> queries; public void PrefromQuery(object send, Query q) { queries?.Invoke(send, q); } }public class Query//查詢物件 { public enum Argument { Attack,//攻擊 Defense//防禦 } public string QueryName; public Argument WhatQuery; public int value; public Query(string queryName, Argument whatQuery, int value) { QueryName= queryName; WhatQuery = whatQuery; this.value = value; } }
定義個生物類
public class Creature { private Game game; //遊戲中介 public string Name;//名稱 private int attack, defense;//攻擊/防禦【私有欄位】 public Creature(Game game, string name, int attack, intdefense) { this.game = game; Name = name; this.attack = attack; this.defense = defense; } public int Attack //對外查詢屬性 通過中介進行查詢 { get { var q = new Query(Name, Query.Argument.Attack, attack); game.PrefromQuery(this, q); return q.value; } } public int Defense //對外防禦屬性,通過中介進行查詢 { get { var q = new Query(Name, Query.Argument.Defense, defense); game.PrefromQuery(this, q); return q.value; } } public override string ToString() { return $"Name:{Name},Attack:{Attack},Defense:{Defense}"; } }
定義一個生物修改抽象模型,實現IDisposable介面,可以再釋放時,執行進一步操作:
傳入遊戲中介和生物,在初始化時繫結自定義事件Handle
public abstract class CreatureModeifier : IDisposable { protected Game game; protected Creature creature; protected CreatureModeifier(Game game, Creature creature) { this.game = game; this.creature = creature; game.queries += Handle; } protected abstract void Handle(object sender, Query q); public void Dispose() { game.queries -= Handle; } }
我們在建立攻擊類和防禦類:實現抽象模型
public class DoubleAttack : CreatureModeifier { public DoubleAttack(Game game, Creature creature) : base(game, creature) { } protected override void Handle(object sender, Query q) { if (q.QueryName== creature.Name && q.WhatQuery == Query.Argument.Attack) { q.value *= 2; } } } public class IncreaseProtectionBuff : CreatureModeifier { public IncreaseProtectionBuff(Game game, Creature creature) : base(game, creature) { } protected override void Handle(object sender, Query q) { if (q.QueryName == creature.Name && q.WhatQuery == Query.Argument.Defense) { q.value += 5; } } }
來看使用:
static void Main(string[] args) { Game game = new Game();//中介 var goblin = new Creature(game, "Goblin", 3, 3);//生物 Console.WriteLine(goblin); using (var doubleAttack=new DoubleAttack(game,goblin))//增加雙倍攻擊BUff { Console.WriteLine(goblin); using (var def = new IncreaseProtectionBuff(game, goblin))//增加防禦BUFF { Console.WriteLine(goblin); } } Console.WriteLine(goblin); }
看看結果:
只在Using範圍內有效。