设计模式-中介者模式

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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值