设计模式(二十一)——中介者模式

中介者模式(Mediator)

中介者模式,用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立改变它们之间的交互。

代码

1.代码如下:

联合国机构类

using System;

namespace Mediator
{
	//联合国机构类
	public abstract class UnitedNations
	{
		//声明
		public abstract void Declare(string message,Country colleague);
	}
}

联合国安全理事会类

using System;

namespace Mediator
{
	//联合国安全理事会
	public class UnitedNationsSecurityCouncil:UnitedNations
	{
		private USA colleague1;
		private Iraq colleague2;
		//美国
		public USA Colleague1{
			set{colleague1=value; }
		}
		//伊拉克
		public Iraq Colleague2{
			set{colleague2=value; }
		}
		//声明
		public override void Declare (string message, Country colleague)
		{
			if (colleague == colleague1) {
				colleague2.GetMessage (message);
			} else {
				colleague1.GetMessage (message);
			}
		}
	}
}

国家类

using System;

namespace Mediator
{
	//国家类
	public abstract class Country
	{
		protected UnitedNations mediator;

		public Country (UnitedNations mediator)
		{
			this.mediator = mediator;
		}
	}
}

美国

using System;

namespace Mediator
{
	//美国
	public class USA:Country
	{
		public USA (UnitedNations mediator):base(mediator)
		{
		}
		//声明
		public void Declare(string message){
			mediator.Declare (message, this);
		}
		//获得消息
		public void GetMessage(string message){
			Console.WriteLine ("美国获得对方信息:" + message);
		}
	}
}

伊拉克

using System;

namespace Mediator
{
	//伊拉克
	public class Iraq:Country
	{
		public Iraq (UnitedNations mediator):base(mediator)
		{
		}
		//声明
		public void Declare(string message){
			mediator.Declare (message, this);
		}
		//获得消息
		public void GetMessage(string message){
			Console.WriteLine ("伊拉克获得对方信息:" + message);
		}
	}
}
2.客户端代码如下:

客户端

using System;

namespace Mediator
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			UnitedNationsSecurityCouncil UNSC = new UnitedNationsSecurityCouncil ();
			USA c1 = new USA (UNSC);
			Iraq c2 = new Iraq (UNSC);

			UNSC.Colleague1 = c1;
			UNSC.Colleague2 = c2;

			c1.Declare ("不准研发核武器,否则要发动战争!");
			c2.Declare ("我们没有核武器,也不怕侵略。");
		}
	}
}
3.运行结果

UML图

源码下载地址 :https://gitee.com/ZhaoYongshuang/DesignPattern.git
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值