May 27, 2021 Design mode
Front Controller Pattern is used to provide a centralized request processing mechanism, and all requests are handled by a single handler. T he handler can do authentication/authorization/log, or track the request, and then pass the request to the appropriate handler. The following are the entities of this design pattern.
We'll create FrontController and Dispatcher as front-end controllers and schedulers, respectively. HomeView and StudentView represent a variety of views created for requests received by the front-end controller.
FrontController Pattern Demo, our demo class uses FrontController to demonstrate front-end controller design patterns.
Create a view.
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"); } }
Create the scheduler 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(); } } }
Create front controller 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); } } }
Use FrontController to demonstrate the front-end controller design pattern.
FrontControllerPatternDemo.java
public class FrontControllerPatternDemo { public static void main(String[] args) { FrontController frontController = new FrontController(); frontController.dispatchRequest("HOME"); frontController.dispatchRequest("STUDENT"); } }
Verify the output.
Page requested: HOME User is authenticated successfully. Displaying Home Page Page requested: STUDENT User is authenticated successfully. Displaying Student Page