java 使用策略模式解决代码中包含太多的if else

1.首先创建一个enum枚举类

    代码附上:

public enum SystemErrorCode {
QUIT(":quit", "", "com.pluster.cloudshiro.utils.PrintQuitCommand"),
ALL(":all", "", "com.pluster.cloudshiro.utils.PrintAllCommand"),
USER(":user", "", "com.pluster.cloudshiro.utils.PrintUserCommand"),
ADMIN(":admin", "", "com.pluster.cloudshiro.utils.PrintAdminCommand"),
AI(":ai", "", "com.pluster.cloudshiro.utils.PrintAiCommand"),
QAI(":qai", "", "com.pluster.cloudshiro.utils.PrintQaiCommand"),
INFO(":info", "", "com.pluster.cloudshiro.utils.PrintInfoCommand");
private String code;
private String desc;
private String clazz;
private static final Map<String, String> err_desc = new HashMap<String, String>();

static {
for (SystemErrorCode refer : SystemErrorCode.values()) {
err_desc.put(refer.getCode(), refer.getClazz());
}
}

private SystemErrorCode(String code, String desc, String clazz) {
this.code = code;
this.desc = desc;
this.clazz = clazz;
}

public static Map<String, String> getAllClazz() {
return err_desc;
}
public static String getDescByCode(int code) {
return err_desc.get(code);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
}

2.定义策略上下文,根据command获取对象实例
代码如下:
public class InnerCommandContext {
@Autowired
static ApplicationContext applicationContext;

public static InnerCommand getInstance(String command) {
//getAllClazz
Map<String, String> allClazz = SystemErrorCode.getAllClazz();
String[] trim = command.trim().split(" ");
String clazz = allClazz.get(trim[0]);
InnerCommand innerCommand = null;
try {
if (StringUtils.isEmpty(clazz)) {
clazz = null;
}
innerCommand = (InnerCommand) Class.forName(clazz).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return innerCommand;
}
}

3.定义接口
代码如下:
public interface InnerCommand {
void process(String msg);
}

4.定义实现类(这里只加了一个实现类,可根据自己业务实现)
代码如下:
public class PrintAdminCommand implements InnerCommand  {
@Override
public void process(String msg) {
System.out.println("aaaaaaaa");
}
}

5.调用
代码如下:
public static void main(String[] args) {
InnerCommand instance = InnerCommandContext.getInstance(":admin");
instance.process(":admin");
}
 
 
 
 
原文地址:https://www.cnblogs.com/niudaxianren/p/12666697.html