枚举策略模式将枚举和策略模式相结合,能使代码更加简洁。以下是消息推送相关的案例
1、定义消息推送接口
package com.bitzh.strategy;
public interface MessagePushStrategy {
void push(String content);
}
2、分别创建邮件推送、短信推送和企业微信推送三个类,实现消息推送接口
package com.bitzh.strategy.impl;
import com.bitzh.strategy.MessagePushStrategy;
public class EmailPushStrategy implements MessagePushStrategy {
public void push(String content) {
System.out.println(String.format("邮件消息推送:%s",content));
}
}
package com.bitzh.strategy.impl;
import com.bitzh.strategy.MessagePushStrategy;
public class SMSPushStrategy implements MessagePushStrategy {
public void push(String content) {
System.out.println(String.format("短信消息推送:%s",content));
}
}
package com.bitzh.strategy.impl;
import com.bitzh.strategy.MessagePushStrategy;
public class WeComPushStrategy implements MessagePushStrategy {
public void push(String content) {
System.out.println(String.format("企业微信消息推送:%s",content));
}
}
3、创建枚举类,将相关策略作为枚举项
package com.bitzh.enums;
import com.bitzh.strategy.MessagePushStrategy;
import com.bitzh.strategy.impl.EmailPushStrategy;
import com.bitzh.strategy.impl.SMSPushStrategy;
import com.bitzh.strategy.impl.WeComPushStrategy;
public enum MessagePushEnum {
EmailPushStrategy("email",new EmailPushStrategy()),
SMSPushStrategy("sms",new SMSPushStrategy()),
WeComPushStrategy("wecom",new WeComPushStrategy());
private String pushType;
private MessagePushStrategy pushStrategy;
MessagePushEnum(String pushType,MessagePushStrategy pushStrategy){
this.pushType = pushType;
this.pushStrategy = pushStrategy;
}
public String getPushType() {
return pushType;
}
public void setPushType(String pushType) {
this.pushType = pushType;
}
public MessagePushStrategy getPushStrategy() {
return pushStrategy;
}
public void setPushStrategy(MessagePushStrategy pushStrategy) {
this.pushStrategy = pushStrategy;
}
public static MessagePushStrategy build(String pushType){
if(pushType == null || "".equals(pushType))
return null;
for(MessagePushEnum pushEnum: MessagePushEnum.values()){
if(pushType.equals(pushEnum.getPushType()))
return pushEnum.getPushStrategy();
}
return null;
}
}
4、进行测试
package com.bitzh;
import com.bitzh.enums.MessagePushEnum;
public class StrategyApplication {
public static void main(String[] args) {
MessagePushEnum.build("email").push("你好!");
MessagePushEnum.build("sms").push("你好!");
MessagePushEnum.build("wecom").push("你好!");
}
}
测试结果: