前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体。

  • 前端控制器(Front Controller) - 处理应用程序所有类型请求的单个处理程序,应用程序可以是基于 web 的应用程序,也可以是基于桌面的应用程序。
  • 调度器(Dispatcher) - 前端控制器可能使用一个调度器对象来调度请求到相应的具体处理程序。
  • 视图(View) - 视图是为请求而创建的对象。

    实现

    我们将创建 FrontControllerDispatcher 分别当作前端控制器和调度器。HomeViewStudentView 表示各种为前端控制器接收到的请求而创建的视图。
    FrontControllerPatternDemo,我们的演示类使用 FrontController 来演示前端控制器设计模式。
    image.png

步骤 1

创建视图。

  1. public class HomeView {
  2. public void show(){
  3. System.out.println("Displaying Home Page");
  4. }
  5. }
  1. public class StudentView {
  2. public void show(){
  3. System.out.println("Displaying Student Page");
  4. }
  5. }

步骤 2

创建调度器 Dispatcher

  1. public class Dispatcher {
  2. private StudentView studentView;
  3. private HomeView homeView;
  4. public Dispatcher(){
  5. studentView = new StudentView();
  6. homeView = new HomeView();
  7. }
  8. public void dispatch(String request){
  9. if(request.equalsIgnoreCase("STUDENT")){
  10. studentView.show();
  11. }else{
  12. homeView.show();
  13. }
  14. }
  15. }

步骤 3

创建前端控制器 FrontController

  1. public class FrontController {
  2. private Dispatcher dispatcher;
  3. public FrontController(){
  4. dispatcher = new Dispatcher();
  5. }
  6. private boolean isAuthenticUser(){
  7. System.out.println("User is authenticated successfully.");
  8. return true;
  9. }
  10. private void trackRequest(String request){
  11. System.out.println("Page requested: " + request);
  12. }
  13. public void dispatchRequest(String request){
  14. //记录每一个请求
  15. trackRequest(request);
  16. //对用户进行身份验证
  17. if(isAuthenticUser()){
  18. dispatcher.dispatch(request);
  19. }
  20. }
  21. }

步骤 4

使用 FrontController 来演示前端控制器设计模式

  1. public class FrontControllerPatternDemo {
  2. public static void main(String[] args) {
  3. FrontController frontController = new FrontController();
  4. frontController.dispatchRequest("HOME");
  5. frontController.dispatchRequest("STUDENT");
  6. }
  7. }

步骤 5

执行程序,输出结果:

  1. Page requested: HOME
  2. User is authenticated successfully.
  3. Displaying Home Page
  4. Page requested: STUDENT
  5. User is authenticated successfully.
  6. Displaying Student Page