前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,全部的请求都将由一个单一的处理程序处理。该处理程序能够作认证/受权/记录日志,或者跟踪请求,而后把请求传给相应的处理程序。如下是这种设计模式的实体。前端
咱们将建立 FrontController、Dispatcher 分别看成前端控制器和调度器。HomeView 和 StudentView 表示各类为前端控制器接收到的请求而建立的视图。web
FrontControllerPatternDemo,咱们的演示类使用 FrontController 来演示前端控制器设计模式。设计模式
建立视图。spa
public class HomeView { public void show(){ System.out.println("Displaying Home Page"); } }
public class StudentView { public void show(){ System.out.println("Displaying Student Page"); } }
建立调度器 Dispatcher。设计
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(); } } }
建立前端控制器 FrontController。日志
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); } } }
使用 FrontController 来演示前端控制器设计模式。code
public class FrontControllerPatternDemo { public static void main(String[] args) { FrontController frontController = new FrontController(); frontController.dispatchRequest("HOME"); frontController.dispatchRequest("STUDENT"); } }
验证输出。对象
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page