- 设计模式-中介模式
- 设计模式-主页
- 设计模式-概述
- 设计模式-工厂模式
- 抽象工厂模式
- 设计模式-Singleton模式
- 设计模式-生成器模式
- 设计模式-原型模式
- 设计模式-适配器模式
- 设计模式-桥梁模式
- 设计模式-过滤器模式
- 设计图案-复合图案
- 设计图案-装饰图案
- 设计图案-立面图案
- 设计图案-飞线图案
- 设计模式-代理模式
- 责任链模式
- 设计模式-命令模式
- 设计模式-解释器模式
- 设计模式-迭代器模式
- 设计模式-中介模式
- 设计模式-Memento模式
- 设计模式-观察者模式
- 设计模式-状态模式
- 设计模式-空对象模式
- 设计模式-战略模式
- 设计模式-模板模式
- 设计模式-访客模式
- 设计模式-MVC模式
- 业务代表模式
- 复合实体模式
- 数据访问对象模式
- 前控制器模式
- 拦截过滤器模式
- 服务定位器模式
- Java传输对象模式
设计模式-中介模式
Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category.
Implementation
We are demonstrating mediator pattern by example of a chat room where multiple users can send message to chat room and it is the responsibility of chat room to show the messages to all users. We have created two classes ChatRoom and User. User objects will use ChatRoom method to share their messages.
MediatorPatternDemo, our demo class, will use User objects to show communication between them.
Step 1
Create mediator class.
ChatRoom.java
import java.util.Date; public class ChatRoom { public static void showMessage(User user, String message){ System.out.println(new Date().toString() + " [" + user.getName() + "] : " + message); } }
Step 2
Create user class
User.java
public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public User(String name){ this.name = name; } public void sendMessage(String message){ ChatRoom.showMessage(this,message); } }
Step 3
Use the User object to show communications between them.
MediatorPatternDemo.java
public class MediatorPatternDemo { public static void main(String[] args) { User robert = new User("Robert"); User john = new User("John"); robert.sendMessage("Hi! John!"); john.sendMessage("Hello! Robert!"); } }
Step 4
Verify the output.
Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John! Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!