23种设计模式【Java】解析 -中介者模式

中介者模式

目的

集中相关对象之间复杂的沟通和控制方式。

类图

角色

  • Mediator: 抽象中介者
  • ConcreteMediator: 具体中介者
  • Colleague: 抽象同事类
  • ConcreteColleague: 具体同事类
    23种设计模式【Java】解析 -中介者模式_第1张图片

实现

这个模式的现实案例最常见就是如其名的 中介 ,就拿租房中介来说,如果让租客和房东直接进行联系,是可以的,但是多对多的关系势必导致 结构 复杂,就需要一个中介。

抽象中介者

public abstract class Mediator {
    //申明一个联络方法
    public abstract void constact(String message,Colleague colleague);
}

具体中介者

这就是你租房时见的中介小哥了。

public class MediatorStructure extends Mediator{
    // 首先中介结构必须知道所有房主和租房者的信息
    private LandlordColleague landlord;
    private TenantColleague tenant;

    public void setColleague(LandlordColleague landlord, TenantColleague tenant) {
        this.landlord = landlord;
        this.tenant = tenant;
    }

    public void constact(String message, Colleague colleague) {
        if(colleague == landlord){          
            //如果是房主,则租房者获得信息
            tenant.getMessage(message);
        } else {       
            // 否者则是房主获得信息
            landlord.getMessage(message);
        }
    }
}

抽象同事类

public abstract class Colleague {
    protected String name;
    protected Mediator mediator;
    
    Colleague(String name,Mediator mediator){
        this.name = name;
        this.mediator = mediator;
    }
    
}

具体同事类

房东
public class LandlordColleague extends Colleague{

    LandlordColleague(String name, Mediator mediator) {
        super(name, mediator);
    }
    
    public void constact(String message){
        mediator.constact(message, this);
    }

    public void getMessage(String message){
        System.out.println("房主:" + name +",获得信息:" + message);
    }
}
租客
public class TenantColleague extends Colleague{

    TenantColleague(String name, Mediator mediator) {
        super(name, mediator);
    }
    
    public void constact(String message){
        mediator.constact(message, this);
    }

    public void getMessage(String message){
        System.out.println("租房者:" + name +",获得信息:" + message);
    }
}

客户端

public class Client {
    public static void main(String[] args) {
        MediatorStructure mediator = new MediatorStructure();
        
        // 房主和租房者只需要知道中介机构即可
        LandlordColleague landlord = new LandlordColleague("张三", mediator);
        TenantColleague tenant = new TenantColleague("李四", mediator);
        
        //中介结构要知道房主和租房者
        mediator.setColleague(landlord, tenant);
        
        tenant.constact("听说你那有房出租");
        landlord.constact("是的");
    }
}

优缺点

优点

  • 简化了对象之间的交互。
  • 将各同事解耦。
  • 减少子类生成。
  • 可以简化各同事类的设计和实现。

缺点

  • 中介者会庞大,变得复杂难以维护。

使用场景

  1. 系统中对象间存在比较复杂的引用关系,导致他们之间的依赖关系结构混乱而且难以复用该对象。
  2. 想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。

JDK 中的使用

  • All scheduleXXX() methods of java.util.Timer
  • java.util.concurrent.Executor#execute()
  • submit() and invokeXXX() methods of java.util.concurrent.ExecutorService
  • scheduleXXX() methods of java.util.concurrent.ScheduledExecutorService
  • [java.lang.reflect.Method#invoke()](

你可能感兴趣的:(设计模式,设计模式)