网站设计模式 专题
您的位置:web > 网站设计模式专题 > 前端控制器模式
前端控制器模式
作者:--    发布时间:2019-11-20

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

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

实现

我们将创建 frontcontrollerdispatcher 分别当作前端控制器和调度器。homeviewstudentview 表示各种为前端控制器接收到的请求而创建的视图。

frontcontrollerpatterndemo,我们的演示类使用 frontcontroller 来演示前端控制器设计模式。

前端控制器模式的 uml 图

步骤 1

创建视图。

homeview.java

public class homeview {
   public void show(){
      system.out.println("displaying home page");
   }
}

studentview.java

public class studentview {
   public void show(){
      system.out.println("displaying student page");
   }
}

步骤 2

创建调度器 dispatcher。

dispatcher.java

public class dispatcher {
   private studentview studentview;
   private homeview homeview;
   public dispatcher(){
      studentview = new studentview();
      homeview = new homeview();
   }

   public void dispatch(string request){
      if(request.equalsignorecase("student")){
         studentview.show();
      }else{
         homeview.show();
      }  
   }
}

步骤 3

创建前端控制器 frontcontroller。

frontcontroller.java

public class frontcontroller {
    
   private dispatcher dispatcher;

   public frontcontroller(){
      dispatcher = new dispatcher();
   }

   private boolean isauthenticuser(){
      system.out.println("user is authenticated successfully.");
      return true;
   }

   private void trackrequest(string request){
      system.out.println("page requested: " + request);
   }

   public void dispatchrequest(string request){
      //记录每一个请求
      trackrequest(request);
      //对用户进行身份验证
      if(isauthenticuser()){
         dispatcher.dispatch(request);
      }    
   }
}

步骤 4

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

frontcontrollerpatterndemo.java

public class frontcontrollerpatterndemo {
   public static void main(string[] args) {
      frontcontroller frontcontroller = new frontcontroller();
      frontcontroller.dispatchrequest("home");
      frontcontroller.dispatchrequest("student");
   }
}

步骤 5

验证输出。

page requested: home
user is authenticated successfully.
displaying home page
page requested: student
user is authenticated successfully.
displaying student page
网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册