設計模式-中介者模式(Mediator)
阿新 • • 發佈:2018-12-08
中介者模式是行為型模式的一種,在Mediator中,類之間的互動行為被統一放在Mediator物件中,物件通過Mediator物件同其他物件互動。
角色和職責:
1.中介者介面(Mediator):
中介者類的抽象父類
2.具體中介者(Concrete Mediator) -:
3.關聯抽象父類(colleague)-:
關聯類的抽象父類
4.具體關聯類(concrete Mediator):
具體關聯類
UML圖:
具體程式碼:
/** * Colleague 抽象類*/ public abstract class Person { private int condition;//條件,條件相同時,才匹配 private String name;//使用者名稱 public Person(String name,int condition,ConcreteMediator mediator){ this.name = name; this.condition = condition; this.mediator = mediator; } protected ConcreteMediator 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; } abstractvoid getPartner(Person persion);//進行匹配 }
/** * 男人 */ public class Man extends Person{ public Man(String name, int condition,ConcreteMediator mediator) { super(name, condition, mediator); } @Override void getPartner(Person person) { this.mediator.setWoman(null);//初始化 this.mediator.setMan(this);//設定自己 this.mediator.contact(person);//去匹配 } }
/** * 女人 */ public class Woman extends Person { public Woman(String name, int condition,ConcreteMediator mediator) { super(name, condition,mediator); } @Override void getPartner(Person person) { this.mediator.setMan(null);//初始化 this.mediator.setWoman(this);//設定自己 this.mediator.contact(person);//去匹配 } }
/** * 中介介面 */ public interface Mediator { void contact(Person person); }
/** * 中介實現類 */ public class ConcreteMediator implements Mediator{ private Man man;//男的 private Woman woman;//女的 @Override public void contact(Person person) {//中介中去匹配 if(person instanceof Man){ this.setMan((Man) person); }else if(person instanceof Woman){ 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() + "不配"); } } public Man getMan() { return man; } public void setMan(Man man) { this.man = man; } public Woman getWoman() { return woman; } public void setWoman(Woman woman) { this.woman = woman; } }
public class Main { public static void main(String[] args) { ConcreteMediator concreteMediator = new ConcreteMediator(); Person zhangsan = new Man("張三",3,concreteMediator); Person xiaohong = new Woman("小紅",2,concreteMediator); Person lisi = new Man("李四",2,concreteMediator); zhangsan.getPartner(xiaohong);//檢視是否相配 zhangsan.getPartner(lisi);//檢視是否相配 lisi.getPartner(xiaohong);//檢視是否相配 } }
結果:
張三和小紅不配
我不是同性戀!
李四和小紅絕配。
原始碼地址::https://github.com/qjm201000/design_pattern_mediator.git