总述
其实这个模式很好理解,非常简单。就是前端一股脑地接收了一大堆请求,然后它根据各个请求的不同进行相应的分派,听上去有点像路由器的意思,实际上也差不多。
类图
类图.png调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
FrontController controller = new FrontController();
controller.receiveRequest(0);
controller.receiveRequest(1);
controller.receiveRequest(2);
controller.receiveRequest(3);
}
}
输出
视图1处理了请求
视图2处理了请求
视图3处理了请求
请求无效
Process finished with exit code 0
前端控制器
package com.company;
public class FrontController {
private Dispatcher dispatcher = new Dispatcher();
public void receiveRequest(int requestID) {
this.dispatcher.dispatchRequest(requestID);
}
}
分派器
package com.company;
public class Dispatcher {
private ViewInterface[] views = {new View1(),new View2(),new View3()};
public void dispatchRequest(int requestIndex) {
if (requestIndex > -1 && requestIndex < views.length) {
this.views[requestIndex].processRequest();
} else {
System.out.println("请求无效");
}
}
}
视图接口
package com.company;
public interface ViewInterface {
public void processRequest();
}
视图1
package com.company;
public class View1 implements ViewInterface {
@Override
public void processRequest() {
System.out.println("视图1处理了请求");
}
}
视图2
package com.company;
public class View2 implements ViewInterface {
@Override
public void processRequest() {
System.out.println("视图2处理了请求");
}
}
视图3
package com.company;
public class View3 implements ViewInterface {
@Override
public void processRequest() {
System.out.println("视图3处理了请求");
}
}
多谢捧场
如果您觉得我的文章有价值,那么赏脸打赏一个,鄙人感激不尽。不过,不打赏看看也是好的,如果有不对的地方,还请您多多指正。
网友评论