1.需求分析
近期笔者在设计mqtt的发布/订阅的主题,其主要采用了设计模式之策略模式,从一定程度解决了多重条件判断带来的代码冗余及紧耦合的问题;
2.使用场景
①如果在一个系统有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为;
②一个系统需要动态地在几种算法中选择一种;
③如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现
3.实现方案
首先贴张UML类图:
①topic策略接口
/** * @auther zx * @date 2018/6/14 11:50 */ public interface TopicStrategy { String getTopic(String userId); }
②发布者(车主及乘客)实现topic策略接口
车主:
public class TopicOfDriverPublish implements TopicStrategy { @Override public String getTopic(String userId) { return TopicPublish.MQTT_PUBLISH_DRIVER_TOPIC+"/"+userId; } }
乘客:
public class TopicOfPassangerPublish implements TopicStrategy { @Override public String getTopic(String userId) { return TopicPublish.MQTT_PUBLISH_PASSANGER_TOPIC+"/"+userId; } }
③订阅者(车主及乘客)实现topic策略接口
车主:
public class TopicOfDriverSubscribe implements TopicStrategy { @Override public String getTopic(String userId) { return TopicSubscribe.MQTT_SUBSCIBE_DRIVER_TOPIC; } }
乘客:
public class TopicOfPassangerSubscribe implements TopicStrategy { @Override public String getTopic(String userId) { return TopicSubscribe.MQTT_SUBSCIBE_PASSANGER_TOPIC; } }
④Context类编写
发布者:
public class TopicPublishContext { private TopicStrategy strategy; public TopicPublishContext(TopicStrategy strategy){ this.strategy = strategy; } public String getTopic(String userId){ return strategy.getTopic(userId); } }
订阅者:
public class TopicSubscribeContext { private TopicStrategy strategy; public TopicSubscribeContext(TopicStrategy strategy){ this.strategy = strategy; } public String getTopic(String userId){ return strategy.getTopic(userId); } }
4.测试用例
public static void main(String[] args) { TopicStrategy strategy1 = new TopicOfDriverPublish(); TopicStrategy strategy2 = new TopicOfPassangerPublish(); TopicStrategy strategy3 = new TopicOfDriverSubscribe(); TopicStrategy strategy4 = new TopicOfPassangerSubscribe(); TopicPublishContext driver = new TopicPublishContext(strategy1); TopicPublishContext passer = new TopicPublishContext(strategy2); TopicSubscribeContext driver1 = new TopicSubscribeContext(strategy3); TopicSubscribeContext passer2 = new TopicSubscribeContext(strategy4); System.out.println("车主发布topic:"+driver.getTopic("123456")); System.out.println("乘客发布topic:"+passer.getTopic("123456")); System.out.println("车主订阅topic:"+driver1.getTopic("123456")); System.out.println("乘客订阅topic:"+passer2.getTopic("123456")); }
效果
好了,我是张星,欢迎加入博主技术交流群,群号:313145288