设计模式 行为型模式 实例 -- 中介者模式实例:一对多聊天
Posted CodeJiao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式 行为型模式 实例 -- 中介者模式实例:一对多聊天相关的知识,希望对你有一定的参考价值。
01:中介者模式
02:设计模式 行为型模式 实例 – 中介者模式实例
1. 中介者模式实例
1.1 需求分析:
多个Student和多个Teacher对象要进行谈话,
一个Student或Teacher可以把一句话对多个对象说,
请用中介者模式实现这一谈话过程。
1.2 类图分析:
类图分析:
1.2 代码实现:
1.2.1 Mediator :抽象中介者类
package ex09.mediator;
import java.util.ArrayList;
/**
* ClassName: Mediator
* Description: 抽象中介者类
*
* @author Tianjiao
* @date 2021/11/22 15:07
*/
public abstract class Mediator
protected ArrayList<People> peopleList = new ArrayList<>();// 用于存储同事对象
/**
* 注册方法:用于新增同事对象
*/
public void register(People people)
peopleList.add(people);
public abstract void talk(String message, People people);
1.2.2 People :抽象同事类
package ex09.mediator;
/**
* ClassName: People
* Description: 抽象同事类
*
* @author Tianjiao
* @date 2021/11/22 15:08
*/
public abstract class People
protected String name;
protected Mediator mediator;
public People(String name, Mediator mediator)
this.name = name;
this.mediator = mediator;
mediator.register(this);
//和中介联系(沟通)
public void talk(String message)
mediator.talk(message, this);
// 获取消息
public abstract void getMsg(String msg, People people);
1.2.3 Student、Teacher :具体同事类
Student :
package ex09.mediator;
/**
* ClassName: Student
* Description: 具体同事类
*
* @author Tianjiao
* @date 2021/11/22 15:17
*/
public class Student extends People
public Student(String name, Mediator mediator)
super(name, mediator);
@Override
public void getMsg(String msg, People people)
System.out.println("学生:" + name + " 收到来自" + people.name + "的消息是:" + msg);
Teacher :
package ex09.mediator;
/**
* ClassName: Teacher
* Description: 具体同事类
*
* @author Tianjiao
* @date 2021/11/22 15:17
*/
public class Teacher extends People
public Teacher(String name, Mediator mediator)
super(name, mediator);
@Override
public void getMsg(String msg, People people)
System.out.println("教师:" + name + " 收到来自" + people.name + "的消息是:" + msg);
1.2.4 ConcreteMediator : 具体中介者
package ex09.mediator;
/**
* ClassName: ConcreteMediator
* Description: 具体中介者
*
* @author Tianjiao
* @date 2021/11/22 15:26
*/
public class ConcreteMediator extends Mediator
@Override
public void talk(String message, People peo)
for (People people : peopleList)
// 让除了本人之外的所有人收到消息
if (people != peo)
people.getMsg(message, peo);
1.2.5 Client : 客户端类
package ex09.mediator;
/**
* ClassName: Client
* Description:客户端类:测试类
*
* @author Tianjiao
* @date 2021/11/22 15:25
*/
public class Client
public static void main(String[] args)
Mediator mediator = new ConcreteMediator();
Teacher teacher01 = new Teacher("教师1", mediator);
Teacher teacher02 = new Teacher("教师2", mediator);
Teacher teacher03 = new Teacher("教师3", mediator);
Student student01 = new Student("学生1", mediator);
Student student02 = new Student("学生2", mediator);
Student student03 = new Student("学生3", mediator);
teacher01.talk("Hello World");
1.2.6 运行结果:
以上是关于设计模式 行为型模式 实例 -- 中介者模式实例:一对多聊天的主要内容,如果未能解决你的问题,请参考以下文章