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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM