21-中介者模式
概念
中介者模式,又叫调停者模式(mediator),用一个中介对象来封装一系列的对象交互。中介者使个对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互
优缺点:
中介者模式很容易在系统中应用,也很容易在系统中误用。当系统出现了"多对多"交互复杂度的对象群时,不要急于使用中介者模式,而要先反思你的系统在设计上是不是合理
中介者模式的出现减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator,由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到他们之间的交互上来,也就是站在一个更宏观的额角度去看待系统
由于concreteMediator控制了集中化,于是就交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个concreteColleague都复杂
中介者模式一般应用于一组对象已定义良好但是复杂的方式进行同心度额场合,以及想定制一个分部在多个类中行为,又不想审查隔行太多子类的场合
举例
package com.gof.mediator;
/**
* 功能描述
*
* @since 2023-03-02
*/
public abstract class Mediator {
public abstract void send(String message, Colleague colleague);
}
package com.gof.mediator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 功能描述
*
* @since 2023-03-02
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ConcreteMediator extends Mediator {
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
@Override
public void send(String message, Colleague colleague) {
if (colleague == colleague1) {
colleague2.notify(message);
} else {
colleague1.notify(message);
}
}
}
package com.gof.mediator;
/**
* 功能描述
*
* @since 2023-03-02
*/
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public void send(String message) {
mediator.send(message, this);
}
public abstract void notify(String message);
}
package com.gof.mediator;
/**
* 功能描述
*
* @since 2023-03-02
*/
public class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
@Override
public void notify(String message) {
System.out.println("同事1得到消息:" + message);
}
}
package com.gof.mediator;
/**
* 功能描述
*
* @since 2023-03-02
*/
public class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
@Override
public void notify(String message) {
System.out.println("同事2得到消息:" + message);
}
}
package com.gof.mediator;
/**
* 功能描述
*
* @since 2023-03-02
*/
public class Client {
public static void main(String[] args) {
ConcreteMediator mediator = new ConcreteMediator();
ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator);
ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);
mediator.setColleague1(colleague1);
mediator.setColleague2(colleague2);
colleague1.send("帮小菜装一下电脑");
colleague2.send("好的");
}
}
标签:Colleague,21,mediator,void,模式,中介,message,public
From: https://www.cnblogs.com/Oh-mydream/p/17171665.html