中介者模式也是用来降低类类之间的耦合的,因为如果类与类之间有依赖关系的话,不利于功能的拓展和维护,因为只要修改一个对象,其它关联的对象都得进行修改。
我们还是来举个栗子:
某网络棋牌室,每一个房间有三个人打牌,平台从赢的人里面抽取5%作为管理费,然后其他人则根据规则赢钱或者输钱。
那么,这个网络平台就是一个中介,打牌的三个人。
代码实现一下
/** * @author: hx * @Time: 2019/5/24 * @Description: Platform */ public interface Platform { void count(Customer winer); } /** * @author: hx * @Time: 2019/5/24 * @Description: HPlatform */ public class HPlatform implements Platform { private Customer m; private Customer h; private Customer w; private double winMoney = 20; public HPlatform(Customer m, Customer h, Customer w) { this.m = m; this.h = h; this.w = w; } @Override public void count(Customer winer) { if (winer instanceof XiaoMing){ m.gamble(winMoney*0.95); h.gamble(-winMoney/2); w.gamble(-winMoney/2); }else if (winer instanceof XiaoHong){ m.gamble(-winMoney/2); h.gamble(winMoney*0.95); w.gamble(-winMoney/2); }else { m.gamble(-winMoney/2); h.gamble(-winMoney/2); w.gamble(winMoney*0.95); } } } /** * @author: hx * @Time: 2019/5/24 * @Description: Customer */ public abstract class Customer { private int money; public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public abstract void gamble(double moneyChange); } /** * @author: hx * @Time: 2019/5/24 * @Description: XiaoHong */ public class XiaoHong extends Customer { public XiaoHong() { setMoney(20); } @Override public void gamble(double moneyChange) { System.out.println("小红剩余金额为:"+(getMoney()+moneyChange)); } } /** * @author: hx * @Time: 2019/5/24 * @Description: XiaoMing */ public class XiaoMing extends Customer { public XiaoMing() { setMoney(20); } @Override public void gamble(double moneyChange) { System.out.println("小明剩余金额:" + (getMoney() + moneyChange)); } } /** * @author: hx * @Time: 2019/5/24 * @Description: XiaoWang */ public class XiaoWang extends Customer { public XiaoWang() { setMoney(20); } @Override public void gamble(double moneyChange) { System.out.println("小王剩余金额为:" + (getMoney() + moneyChange)); } }玩一把游戏
public static void main(String[] args){ Customer m = new XiaoMing(); Customer h = new XiaoHong(); Customer w = new XiaoWang(); Platform platform = new HPlatform(m,h,w); platform.count(m); } 输出结果: 小明剩余金额:39.0 小红剩余金额为:10.0 小王剩余金额为:10.0代码其实看起来有点复杂
这样管理用户其实很复杂,在实际中,其实是结合观察者模式来使用的。中介者模式主要将涉及到多方的数据处理,集中起来处理,所以也是很符合一个座位中介者的身份,处理多方之间的关系
实际运用,可以结合观察者模式来处理,在发布类中可以对多方数据进行处理。
可以参考我写的观察者模式的内容