设计模式-中介者模式

tech2022-07-06  242

中介者模式,针对多个对象之间有相互交叉影响的关系,系统复杂耦合关系多的。为了降低耦合度,单独创建一个中介类,用来管理跟个模块之间的耦合关系。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MediatorSample { class Program { static void Main(string[] args) { Player PlayerA = new Player(100, "PlayerA"); Player PlayerB = new Player(100, "PlayerB"); Player PlayerC = new Player(100, "PlayerC"); List<Component> Players = new List<Component> { PlayerA, PlayerB, PlayerC }; ConectMediator Mediation = new ConectMediator(Players); PlayerA.Chenged(); PlayerC.Chenged(); Console.ReadLine(); } } abstract class Mediator { public abstract void ComponentChanged(Component Player); public List<Component> Players; public Mediator(List<Component> players) { Players = players; foreach (var h in Players) { h.SetMediator(this); } } } class ConectMediator:Mediator { public ConectMediator(List<Component> players):base(players) { } public int MoneyPerTimes=30; public override void ComponentChanged(Component Player) { foreach(var h in Players) { if (h.name == Player.name) { h.Won(MoneyPerTimes); } else h.Lose((int)(MoneyPerTimes / (Players.Count - 1))); } } } abstract class Component { public string name;//玩家名字 public int Money;//玩家金钱 protected Mediator mediator; public void SetMediator(Mediator mediator) { this.mediator = mediator; } //变动 默认是赢了 public void Chenged() { mediator.ComponentChanged(this); } //赢了钱 public abstract void Won(int money); //输了钱 public abstract void Lose(int money); } class Player:Component { public Player(int money,string name) { this.Money = money; this.name = name; } public override void Won(int money) { Money=+money; Console.WriteLine(name +"玩家赢了"+money); } public override void Lose(int money) { Money = -money; Console.WriteLine(name + "玩家输了" + money); } } }

最新回复(0)