责任链模式(Chain of Responsibility Pattern)
需要了解更多可以参考这篇文章深入剖析 MyBatis 的内部设计和架构设计的实现细节
【情景模式】
在处理MQTT消息的时候,需要根据不同的Topic进行不同的处理,平时我们可以直接使用简单工厂。如下:
//消息处理接口
public interface MessageHandler {
void handleMessage(String message);
}
定义具体的消息处理类:
public class Topic1Handler implements MessageHandler {
@Override
public void handleMessage(String message) {
System.out.println("处理test1消息");
}
}
public class Topic2Handler implements MessageHandler {
@Override
public void handleMessage(String message) {
System.out.println("处理Test2消息");
}
}
public class Topic3Handler implements MessageHandler {
@Override
public void handleMessage(String message) {
System.out.println("处理Test3消息");
}
}
定义简单工厂,根据不同的topic返回不同的对象:
public class MessageHandlerFactory {
private static Topic1Handler topic1Handler = new Topic1Handler();
private static Topic2Handler topic2Handler = new Topic2Handler();
private static Topic3Handler topic3Handler = new Topic3Handler();
public static MessageHandler createMessageHandler(String topic) {
switch (topic) {
case "/topic/topic1/":
return topic1Handler;
case "/topic/topic2/":
return topic2Handler;
case "/topic/topic3/":
return topic3Handler;
default:
throw new UnsupportedOperationException("无法处理的topic"