Front Controller pattern
Front Controller pattern (Front Controller Pattern) is used to provide a centralized mechanism for handling requests, all requests are processed by a single handler. The handler can do authentication / authorization / logging or tracking request, then the request to the appropriate handler. The following is an entity of this design pattern.
- Front Controller (Front Controller) - a single handler to process all types of requests an application, the application may be a web-based application that can be desktop-based applications.
- Scheduler (Dispatcher) - front-end controller may use a dispatcher object to dispatch the request to the appropriate specific handler.
- View (View) - view is the object of the request and created.
achieve
We will createFrontController,Dispatcher, respectively, as the front-end controller and scheduler.HomeViewandStudentViewview showing a variety of front-end controller receives a request to create.
FrontControllerPatternDemo,our demonstration class to demonstrate the useFrontControllerFront Controller design pattern.
step 1
Create the 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"); } }
Step 2
Create dispatcher 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 (); } } }
Step 3
Creating a front controller FrontController.
Context.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) { // Record every request trackRequest (request); // To authenticate the user if (isAuthenticUser ()) { dispatcher.dispatch (request); } } }
Step 4
FrontControllerto demonstrate the use of the Front Controller design pattern.
FrontControllerPatternDemo.java
public class FrontControllerPatternDemo { public static void main (String [] args) { FrontController frontController = new FrontController (); frontController.dispatchRequest ( "HOME"); frontController.dispatchRequest ( "STUDENT"); } }
Step 5
Verify output.
Page requested: HOME User is authenticated successfully. Displaying Home Page Page requested: STUDENT User is authenticated successfully. Displaying Student Page