java - 枚举的访问者设计模式
问题描述
我从客户端收到给定参数类型和十六进制值的响应。根据参数类型,我知道它指的是什么类型的参数,我可以构建特定的参数。
我想找到一种设计模式,让我摆脱显式参数类型检查:
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;
}
....
解决方案
我在这里看不到访客模式。
你需要的是工厂模式:
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();
}
}
}
推荐阅读
- excel - 西班牙语的Excel图表轴日期格式,没有点的月份
- sql - 根据另一个表更新一个表中每个学生的最高分
- python - 在 Django 中返回错误的 URL
- android - 如何在 Windows 7 笔记本电脑中拦截/查看来自 android 设备的肥皂请求和响应?
- mysql - 与“创建表为”类似的功能,但添加更多信息
- python - 用于计算 2 列中的值的 Pandas groupby/pivot 表
- css - 如何用css减少这个字母“、”中的空格?
- gitlab - 使用 PWD 在 .gitlab-ci.yml 中定义变量时出错
- pandas - cannot read csv with date parsing, dtypes and chunksize
- jenkins - 传递给 MsBuild 的 Arg 在 PostBuildEvent 上无法识别