设计模式——中介者模式
作者:互联网
很常用的一种设计模式,比如所谓的MVP架构就是典型的中介者模式
MVC 框架时代, M V C 三者之间皆可以相互操作,导致后期维护的难度升高,之后就引入了MVP架构来进行解耦,本质就是使用中介者模式的思想。
这里就不多做解释了,大家应该都用过MVP吧
还是举个例子:
现在有n个买家和n个卖家;他们如果相互交流就会比较麻烦,比较乱,我们引入一个中介(对,就像现实的中间商)来对接两头就ok了。
定义买方中介接口
public interface SolderMediary {
void sendMessageToBuyer(String msg);
}
定义卖方中介接口
public interface BuyerMediary {
void sendMessageToSolder(String msg);
}
定义中介者
public class Market implements SolderMediary, BuyerMediary {
private Buyer buyer;
private Solder solder;
public void setBuyer(Buyer buyer) {
this.buyer = buyer;
}
public void setSolder(Solder solder) {
this.solder = solder;
}
@Override
public void sendMessageToSolder(String msg) {
super.sendMessage(msg);
solder.handleMsg(msg);
}
@Override
public void sendMessageToBuyer(String msg) {
super.sendMessage(msg);
buyer.handleMsg(msg)
}
}
定义卖方类
public class Solder {
BuyerMediary mediary;
public Solder(BuyerMediary mediary) {
this.mediary = mediary;
}
void sendMessage(String message) {
this.mediary.sendMessageToBuyer(message);
}
}
定义买方类
public class Buyer {
SolderMediary mediary;
public Buyer(SolderMediary mediary) {
this.mediary = mediary;
}
@Override
void sendMessage(String message) {
super.sendMessage(message);
this.mediary.sendMessageToSolder(message);
}
}
标签:String,void,模式,中介,msg,solder,设计模式,mediary,public 来源: https://www.cnblogs.com/gradyblog/p/15358363.html