package com.maom.design.D_18_Mediator;
/**
* @Title: D_18_Mediator
* @Description: 18_中介者模式
* @Author maohb
* @Version 1.0
*/
public class D_18_Mediator {
public static void main(String[] args) {
// 中介者对象 判断方法集中
Mediator mediator = new Mediator();
Person zhangsan = new Man("张三",7,mediator);
Person lisi = new Man("李四",7,mediator);
Person xiaofang = new Woman("小小芳",7,mediator);
zhangsan.getPartner(lisi);
xiaofang.getPartner(lisi);
}
}
/** 中介者类 */
class Mediator {
private Man man;
private Woman woman;
public void setMan(Man man) {
this.man = man;
}
public void setWoman(Woman woman) {
this.woman = woman;
}
/** 中介方法 */
public void getPartner(Person person) {
//将搭档设置上
if (person instanceof Man)
this.setMan((Man) person);
else
this.setWoman((Woman) person);
//判断条件
if (man == null || woman == null) {
System.out.println("吖,我可不是同性恋!");
}
else {
if (man.getCondition() == woman.getCondition())
System.out.println(man.getName() + "和" + woman.getName() + "绝配");
else
System.out.println(man.getName() + "和" + woman.getName() + "不匹配");
}
}
}
abstract class Person {
private String name;
private int condition;
private Mediator mediator;
public Person(String name, int condition, Mediator mediator) {
super();
this.name = name;
this.condition = condition;
this.mediator = mediator;
}
public Mediator getMediator() {
return mediator;
}
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCondition() {
return condition;
}
public void setCondition(int condition) {
this.condition = condition;
}
// 抽象中介方法
public abstract void getPartner(Person person);
}
class Man extends Person {
public Man(String name, int condition, Mediator mediator) {
super(name, condition, mediator);
}
public void getPartner(Person person) {
this.getMediator().setMan(this);
this.getMediator().getPartner(person); // 调用中介者方法
}
}
class Woman extends Person {
public Woman(String name, int condition, Mediator mediator) {
super(name, condition, mediator);
}
public void getPartner(Person person) {
this.getMediator().setWoman(this);
this.getMediator().getPartner(person);
}
}
设计模式笔记_18_中介者模式
最新推荐文章于 2024-09-10 17:07:09 发布