使用面向对象技术替代switch-case和if-else

在日常开发中,常常会作一些状态判断,用到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.使用继承子类多态

使用继承子类多态的方式,通常对于某个具体对象,它的状态是不可改变的(在对象的生存周期中)。

现在使用四个子类分别代表四种类型的方法。这样就可以使用多态将各个方法的具体逻辑分置到子类中去了。

在抽象基类Method中可以提供创建子类实例的静态方法,当然也可以使用Simple FacTory模式。对于getMethod()方法,延迟到子类中实现;对于safeMethod()方法和passwordRequired()方法,提供一个默认的实现,这个实现应该符合绝大部分子类的要求,这样的话,对于少数不符合默认实现的子类只需override相应方法即可。

Method.java

package com.zj.subclass;public abstract class Method {   public final static Method createPostMethod() {    return new PostMethod();   }   public final static Method createGetMethod() {    return new GetMethod();   }   public final static Method createPutMethod() {    return new PutMethod();   }   public final static Method createDeleteMethod() {    return new DelMethod();   }   abstract public String getMethod();   public boolean safeMethod() {    return false;   }   public boolean passwordRequired() {    return true;   }}

四个子类分别继承和override相应的方法。

PostMethod.java

package com.zj.subclass;public class PostMethod extends Method {   @Override   public String getMethod() {    return "This is POST method";   }   @Override   public boolean passwordRequired() {    return false;   }}

GetMethod.java

package com.zj.subclass;public class GetMethod extends Method{   @Override   public String getMethod() {    return "This is GET method";   }   @Override   public boolean safeMethod() {    return true;   }}

PutMethod.java

package com.zj.subclass;public class PutMethod extends Method {   @Override   public String getMethod() {    return "This is PUT method";   }}

DelMethod.java

package com.zj.subclass;public class DelMethod extends Method{   @Override   public String getMethod(){    return "This is DELETE method";   }}

2.使用state模式

如果希望对象在生存周期内,可以变化自己的状态,则可以选择state模式。

这里抽象状态为一个接口MethodType,四种不同的状态实现该接口。

<<i 家!甜蜜的家!天下最美好的莫过於家

使用面向对象技术替代switch-case和if-else

相关文章:

你感兴趣的文章:

标签云: