设计模式之中介模式
设计模式 Java About 3,092 words作用
用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
原理
Mediator:抽象中介类,定义了同事对象到中介者对象的接口。
ConcreteMediator:具体中介类,实现抽象方法,他需要知道所有的具体的同事类,即以一个集合来管理HashMap,并接受某个同事对象消息,完成相应的任务。
Colleague:抽象同事类
ConcreteColleague:具体的同事类,每个同事只知道自己的行为,而不了解其他同事类的行为(方法),但是他们都依赖中介者对象。
案例
Mediator
public interface Mediator {
void register(String colleagueName, Colleague colleague);
void getMessage(int stateChange, String colleagueName);
void sendMessage();
}
ConcreteMediator
public class ConcreteMediator implements Mediator {
private Map<String, Colleague> colleagueMap;
private Map<String, String> interMap;
public ConcreteMediator() {
colleagueMap = new HashMap<>();
interMap = new HashMap<>();
}
@Override
public void register(String colleagueName, Colleague colleague) {
colleagueMap.put(colleagueName, colleague);
if (colleague instanceof Alarm) {
interMap.put("alarm", colleagueName);
} else if (colleague instanceof TV) {
interMap.put("tv", colleagueName);
}
}
@Override
public void getMessage(int stateChange, String colleagueName) {
if (colleagueMap.get(colleagueName) instanceof Alarm) {
if (stateChange == 0) {
String tv = interMap.get("tv");
TV tvColleague = (TV) colleagueMap.get(tv);
tvColleague.startTV();
} else if (stateChange == 1) {
String tv = interMap.get("tv");
TV tvColleague = (TV) colleagueMap.get(tv);
tvColleague.stopTV();
}
}
}
@Override
public void sendMessage() {
}
}
Colleague
public abstract class Colleague {
private Mediator mediator;
public String name;
public Colleague(Mediator mediator, String name) {
this.mediator = mediator;
this.name = name;
}
public Mediator getMediator() {
return mediator;
}
public abstract void sendMessage(int stateChange);
}
ConcreteColleague
public class Alarm extends Colleague {
public Alarm(Mediator mediator, String name) {
super(mediator, name);
mediator.register(name, this);
}
@Override
public void sendMessage(int stateChange) {
getMediator().getMessage(stateChange, this.name);
}
}
public class TV extends Colleague {
public TV(Mediator mediator, String name) {
super(mediator, name);
mediator.register(name, this);
}
@Override
public void sendMessage(int stateChange) {
getMediator().getMessage(stateChange, this.name);
}
public void startTV() {
System.out.println("Start TV!");
}
public void stopTV() {
System.out.println("Stop TV!");
}
}
调用
public class Client {
public static void main(String[] args) {
Mediator mediator = new ConcreteMediator();
Alarm alarm = new Alarm(mediator, "alarm");
TV tv = new TV(mediator, "tv");
alarm.sendMessage(0);
alarm.sendMessage(1);
}
}
Views: 2,358 · Posted: 2019-12-30
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...