使用面向对象技术替代switch-case和if-else2011-03-23zhangjunhd在日常开发中,常常会作一些状态判断,用到swich-case与if-else。在面向对象的环境里,有两种方式可以替代它们。一种是使用继承子类的多态,另一种是使用state模式。它们使用对象的间接性有效地摆脱了传统的状态判断。举个例子。Method.java
package com.zj.original;
import com.zj.utils.NoMethodTypeException;
public class Method {
private int _type;
public static final int POST = 0;
public static final int GET = 1;
public static final int PUT = 2;
public static final int DELETE = 3;
public Method(int type) {
_type = type;
}
public String getMethod() throws NoMethodTypeException {
switch (_type) {
case POST:
return "This is POST method";
case GET:
return "This is GET method";
case PUT:
return "This is PUT method";
case DELETE:
return "This is DELETE method";
default:
throw new NoMethodTypeException();
}
}
public boolean safeMethod() {
if (_type == GET)
return true;
else
return false;
}
public boolean passwordRequired() {
if (_type == POST)
return false;
else
return true;
}
}类Method中,存在四个状态Post、Get、Put和Delete。有一个switch-case判断,用于输出四种方法的描述信息;两个if-else判断,分别判断方法是否安全(只有Get方法是安全的),方法是否需要密码(只有Post方法不需要密码)。1.使用继承子类多态使用继承子类多态的方式,通常对于某个具体对象,它的状态是不可改变的(在对象的生存周期中)。