设计模式之中介者模式

中介者模式,最近因为某种原因(穷),导致要买二手车挂指标。正好拿来当中介者模式的例子。

中介者模式UML.png
abstract class Mediator{
    protected BuyCarPeople buyer;
    protected SoldCarPeople solder;
    
    public abstract void work();
    
    public void setBuyCarPeople(BuyCarPeople buyer){
        this.buyer = buyer;
    }
    
    public void setSoldCarPeople(SoldCarPeople solder){
        this.solder = solder;
    }
}

抽象中介者,抽象方法work是中介的职责

class GuaZiMediator extends Mediator{
    public void work(){
        getCarInfo();
        getMoneyFromBuyer();
        //中间抽层
        giveMoneyForSolder();
        giveCarForBuyer();
    }
    
    private void getCarInfo(){
        solder.actionToMediator();
    }
    
    private void getMoneyFromBuyer(){
        buyer.actionToMediator();
    }
    
    private void giveMoneyForSolder(){
        solder.actionFromMediator();
    }
    
    private void giveCarForBuyer(){
        buyer.actionFromMediator();
    }
}

具体的中介者,在买卖二手车这件事情之中,完全对接买卖双发,中间干点羞羞的事情

abstract class People{
    protected Mediator mediator;
    public People(Mediator mediator){
        this.mediator = mediator;
    }
    abstract void actionToMediator();
    abstract void actionFromMediator();
}

抽象买二手车的买卖双方

class BuyCarPeople extends People{
    public BuyCarPeople(Mediator mediator){
        super(mediator);
    }
    
    public void actionToMediator(){
        // 把钱给中介
    }
    
    public void actionFromMediator(){
        //中介给我车
    }
}

买车人

class SoldCarPeople extends People{
    public SoldCarPeople(Mediator mediator){
        super(mediator);
    }
    
    public void actionToMediator(){
        //把车给中介 帮忙卖
    }
    
    public void actionFromMediator(){
        //中介把卖车钱给我
    }
}

卖车人

public class Client{
    Mediator mediator = new GuaZiMediator();
    SolderCarPeople solder = new SolderCarPeople(mediator);
    BuyCarPeople buyer = new BuyCarPeople(mediator);
    mediator.setBuyCarPeople(buyer);
    mediator.setSoldCarPeople(solder);
    mediator.work();//中介帮忙买卖车
}

客户端

个人总结

当两个或者更多的对象之间要相互调用,互相持有是很麻烦的事情。引入中介者模式,中介者类会联系各方,所有的方法需求都通过中介者转达。中介者持有所有各个对象完成交互。

推荐阅读更多精彩内容