Easy Tutorial
❮ State Pattern Visitor Pattern ❯

Front Controller Pattern

The Front Controller Pattern is used to provide a centralized request handling mechanism so that all requests are handled by a single handler. This handler can do the authentication/authorization/logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.

Implementation

We'll create FrontController and Dispatcher as the Front Controller and Dispatcher respectively. HomeView and StudentView represent various views for the requests that the Front Controller receives.

FrontControllerPatternDemo, our demo class, will use FrontController to demonstrate the Front Controller Design Pattern.

Step 1

Create Views.

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 the 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

Create the Front Controller.

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){
      // Log each request
      trackRequest(request);
      // Authenticate the user
      if(isAuthenticUser()){
         dispatcher.dispatch(request);
      }  
   }
}

Step 4

Use FrontController to demonstrate 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

Execute the program, output results:

Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page
❮ State Pattern Visitor Pattern ❯