大话设计模式_中介者模式

以美国和伊拉克通话要通过联合国安全理事会来传递.

package com.wzs.design;

/**
 * 大话设计模式--page262 中介者模式
 * 
 * @author Administrator
 * 
 */
public class MediatorPattern {
	public static void main(String[] args) {
		UnitedNationsSecurityCouncil unsc = new UnitedNationsSecurityCouncil();

		USA c1 = new USA(unsc);
		Iraq c2 = new Iraq(unsc);

		unsc.setColleague1(c1);
		unsc.setColleague2(c2);

		c1.declare("不准研制和武器,否则要发动战争!");
		c2.declare("我们没有核武器,也不怕侵略.");
	}
}

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

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

// 美国
class USA extends Country {

	public USA(UnitedNations mediator) {
		super(mediator);
	}

	public void declare(String message) {
		mediator.declare(message, this);
	}

	public void getMessage(String message) {
		System.out.println("美国获得对方信息:" + message);
	}
}

// 伊拉克
class Iraq extends Country {

	public Iraq(UnitedNations mediator) {
		super(mediator);
	}

	public void declare(String message) {
		mediator.declare(message, this);
	}

	public void getMessage(String message) {
		System.out.println("伊拉克获得对方信息:" + message);
	}
}

// 联合国机构类
abstract class UnitedNations {
	public abstract void declare(String message, Country colleague);
}

// 联合国安全理事会
class UnitedNationsSecurityCouncil extends UnitedNations {
	private USA colleague1;
	private Iraq colleague2;

	// 美国
	public void setColleague1(USA colleague1) {
		this.colleague1 = colleague1;
	}

	// 伊拉克
	public void setColleague2(Iraq colleague2) {
		this.colleague2 = colleague2;
	}

	@Override
	public void declare(String message, Country colleague) {
		if (colleague == colleague1) {
			colleague1.getMessage(message);
		} else {
			colleague2.getMessage(message);
		}
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值