首页 > 技术文章 > 设计模式-行为型模式-中介者模式

chenyongblog 2016-03-26 19:35 原文

中介者要解决的问题

中介者模式(Mediator Pattern)是用来降低多个对象和类之间通信的复杂度。这种模式提供了一个中介类,该类通常用来处理不同类之间的通信。中介者模式符合迪米特原则,即一个类应当尽量减少与其他类的联系。

实例描述

在我们现实生活中就有这样的例子,你如果去租房,你可能会在网站上找一些发布租房的信息,找到对应的房东。为了能够找到性价比高的房子,你可能找好多家,那么你都要和这些房东打交道,留下电话啥的。有时候房子不好出租的情况下,房东还会主动联系你,就有了下面这幅图:

我们可以看到每个房客(对象)都要和房东(类)打交道,违背了迪米特原则,于是在某种驱动下(可以是利益),中介者的角色产生了

房客只需要把自己想租房子的类型(价格,位置。。)告诉中介,房东只需要把房子出租的信息在中介那里备案,那么我们可以看到在这里房东对房客是不可见的,也就减少了依赖,房东和房客只需要关注中介就好了,我们在这里加入观察者模式就能起到通知房客和房东的功能。

下面是我根据这种情景写的Demo,只是简单的演示,设计模式只可意会不可言传

抽象Person类,房客和房东都继承自Person

public abstract class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    abstract void say();
}

房东类Landlord

public class Landlord extends Person {
    public Landlord() {
    }

    public Landlord(String name) {
        this.setName(name);
    }

    @Override
    void say() {
        System.out.println(String.format("I am Landlord, my name is ? I have two rooms, each 800$...", this.getName()));
    }

}

房客类Renter

public class Renter extends Person {

    public Renter() {}

    public Renter(String name) {
        this.setName(name);
    }
    @Override
    void say() {
        System.out.println(String.format("I am Renter, my name is ?, I only want to rent a room less than 500$", this.getName()));
    }

}

中介者接口

public interface IMediator {
    void showMessage(Person person);
}

中介者的具体实现

public class Mediator implements IMediator{

    @Override
    public void showMessage(Person person) {
        person.say();
    }
}

具体调用

    public static void executeMediatorPattern() {
        System.out.println("Mediator Design Pattern:");
        Landlord landlord = new Landlord("Fang Da Da");
        Renter renter = new Renter("Zhu Fang Fang");
        IMediator mediator = new Mediator();

        mediator.showMessage(landlord);
        mediator.showMessage(renter);
        System.out.println("End...................");
    }

 

 

推荐阅读