中介者模式是一种行为模式,中介者模式中的中介者类协调多个类对象的交互行为,减少耦合。MVC模式中的controller是中介者模式的典型应用,controller作为中介者,协调model和view之间的交互。下面以简单的股票交易为例说明中介者模式。
股民类:ShareHolder.java
public class ShareHolder {
private long id;
private int share;
private double money;
private StockExchange se;
public ShareHolder(long id, int share, double money, StockExchange se) {
this.id = id;
this.share = share;
this.money = money;
this.se = se;
}
public void exchange(int exShare, ShareHolder other) {
this.se.exchange(this, other, exShare);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getShare() {
return share;
}
public void setShare(int share) {
this.share = share;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return this.id + ":: share: " + this.share + ", money: " + this.money;
}
}
股票交易所类:StockExchange.java,中介者类
public class StockExchange {
private double price;
public StockExchange(double initPrice) {
this.price = initPrice;
}
public void exchange(ShareHolder holder1, ShareHolder holder2, int shareToExchange) {
int newShare1 = holder1.getShare() + shareToExchange, newShare2 = holder2.getShare() - shareToExchange;
double newMoney1 = holder1.getMoney() - this.price * ((double) shareToExchange), newMoney2 = holder2.getMoney() + this.price * ((double) shareToExchange);
if (newShare1 < 0 || newShare2 < 0 || newMoney1 < 0 || newMoney2 < 0) {
System.out.println("Invalid exchange. Exchange canceled");
} else {
holder1.setShare(newShare1);
holder1.setMoney(newMoney1);
holder2.setShare(newShare2);
holder2.setMoney(newMoney2);
}
}
}
驱动类:Main.java
public class Main {
public static void main(String[] args) {
StockExchange se = new StockExchange(1.0);
ShareHolder sh1 = new ShareHolder(0L, 0, 1000.0, se), sh2 = new ShareHolder(1L, 200, 500.0, se);
sh1.exchange(100, sh2);
System.out.println(sh1); // 0:: share: 100, money: 900.0
System.out.println(sh2); // 1:: share: 100, money: 600.0
}
}
这个例子对于股票交易的模拟过于简单,因此可能体现不出中介者模式的优势。实际上的股票交易中,卖方是不知道具体的买方的,买方也是不知道具体的卖方的,如果没有中介者类,则股民类的交易方法中需要传入所有股民的列表,这是很不合理的设计,此时中介者(股票交易所)的必要性就显现出来了。