900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java 很多if_java 使用策略模式解决代码中包含太多的if else

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

时间:2020-12-04 11:55:46

相关推荐

java 很多if_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 err_desc = new HashMap();

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 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 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");

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。