首页 > 解决方案 > 枚举的访问者设计模式

问题描述

我从客户端收到给定参数类型和十六进制值的响应。根据参数类型,我知道它指的是什么类型的参数,我可以构建特定的参数。

我想找到一种设计模式,让我摆脱显式参数类型检查:

if (paramType != reponse.paramType)

此外,我希望受到编译器错误的保护,当将来我们添加新的 ParameterType 时,不会错过响应参数解析器。

我想使用访问者设计模式,但我相信它不会工作,因为 ParameterType 是一个枚举。

模型:

enum ParameterType {
    NAME, 
    PHOTO,
    ...
    ;
}

class Response {
    ParameterType paramType;
    String value;
}

interface IParameter {}
 
class ParameterName implements IParameter {
    static ParameterType paramType = ParameterType.NAME;
    ParameterName fromReponse(response) {
        if (paramType != reponse.paramType) {
            throw new Exception();
        }
        return parse(response);
    }
    ParameterName parse();
}

class ParameterPhoto implements IParameter  { 
    static ParameterType paramType = ParameterType.PHOTO;
    ParameterPhoto fromReponse(response) {
        if (paramType != reponse.paramType) {
            throw new Exception();
        }
        return parse(response);
    }
    ParameterPhoto parse();
}   

...

服务:

ParameterName getParameterName() {
    var response = client.getName();
    var param = ParameterName.fromResponse(response);
    return param;
}

ParameterPhoto getParameterPhoto() {
    var response = client.getPhoto();
    var param = ParameterPhoto.fromResponse(response);
    return param;
}

....

标签: javadesign-patterns

解决方案


我在这里看不到访客模式。

你需要的是工厂模式:

class ParameterFactory {
 public static IParameter getInstance(ParameterType paramType) {
   //Can use switch here if more options
   if (paramType==ParameterType.NAME) {
     return new NameParameter();
   } else {
     return new PhotoParameter();
    }
 }
}

推荐阅读