中介者模式

中介者模式是一种行为模式,中介者模式中的中介者类协调多个类对象的交互行为,减少耦合。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
    }
}

这个例子对于股票交易的模拟过于简单,因此可能体现不出中介者模式的优势。实际上的股票交易中,卖方是不知道具体的买方的,买方也是不知道具体的卖方的,如果没有中介者类,则股民类的交易方法中需要传入所有股民的列表,这是很不合理的设计,此时中介者(股票交易所)的必要性就显现出来了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值