Java 针对不同请求类型正确选择设计模式
这里有一个关于设计的非常有趣的问题。构建一个API,该API对传递给scan API的请求进行扫描。目前有两种类型的请求,它们彼此完全不同。API必须支持这两个请求。此外,如果将来引入任何新的要求,该设计应该能够很好地工作 请求1:Java 针对不同请求类型正确选择设计模式,java,oop,design-patterns,Java,Oop,Design Patterns,这里有一个关于设计的非常有趣的问题。构建一个API,该API对传递给scan API的请求进行扫描。目前有两种类型的请求,它们彼此完全不同。API必须支持这两个请求。此外,如果将来引入任何新的要求,该设计应该能够很好地工作 请求1: class EmployeeReq { String name; String id; //getter,setter for the parameters. getName(); setName(name);
class EmployeeReq {
String name;
String id;
//getter,setter for the parameters.
getName(); setName(name);
getId(); setId(id);
}
请求2:
class StudentReq {
String studentName;
String grade;
//getter,setter for the parameters.
getStudentName(); setStudentName(studentName);
getGrade(); setGrade(grade);
}
API:
MyRequest:是EmployeeReq还是StudentReq,取决于客户发送的内容
public MyResponse scan(MyRequest req) {
//scan the request based on what parameters being passed as request.
/**
The scan engine should scan the req fields coming in.
Which can be getName(); getId(); getStudentName(); getGrade();
How can I achieve to access the different scan fields from different Request types at once place?
**/
}
“程序到接口,而不是实现”是一件好事
这有用吗
import java.util.HashMap;
import java.util.Map;
interface Request {
String getType();
}
interface Response {
// have method to return whatever response you want to return
}
interface RequestProcessor {
Response process(Request request);
}
class StudentRequest implements Request {
@Override
public String getType() {
return "student";
}
}
class EmployeeRequest implements Request {
@Override
public String getType() {
return "empoloyee";
}
}
class StudentRequestProcessor implements RequestProcessor {
// Process request
@Override
public Response process(Request request) {
return null;
}
}
final class Registry {
// Singleton class
private static Registry INSTANCE = new Registry();
public static Registry getInstance() {
return INSTANCE;
}
private Map<String, RequestProcessor> processors = new HashMap<>();
private Registry() {
processors.put("student", new StudentRequestProcessor());
}
public RequestProcessor getRequestProcessor(Request request) {
return processors.get(request.getType());
}
}
import java.util.HashMap;
导入java.util.Map;
接口请求{
字符串getType();
}
界面响应{
//方法返回您想要返回的任何响应
}
接口请求处理器{
响应过程(请求);
}
类StudentRequest实现请求{
@凌驾
公共字符串getType(){
返回“学生”;
}
}
类EmployeeRequest实现请求{
@凌驾
公共字符串getType(){
返回“雇员”;
}
}
类StudentRequestProcessor实现RequestProcessor{
//处理请求
@凌驾
公共响应过程(请求){
返回null;
}
}
最终类注册表{
//独生子女班
私有静态注册表实例=新注册表();
公共静态注册表getInstance(){
返回实例;
}
私有映射处理器=新的HashMap();
私人注册处(){
processors.put(“学生”,新StudentRequestProcessor());
}
公共请求处理器getRequestProcessor(请求请求){
返回处理器.get(request.getType());
}
}
基本上,您想知道对象是否是某个对象的实例,请尝试以下操作:
if (obj instanceof Class) {
// Your code.
}