Front Controller Pattern

Front Controller design pattern is used to provide a centralized request handling mechanism so that all requests will be 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 design pattern :

  • Front Controller – Single handler for all kinds of requests coming to the application (web or desktop based)
  • Dispatcher – Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler
  • View – Views are the object for which the requests are made

An example below shows the use of Front Controller design pattern.

Front Controller Pattern UML Diagram

Step 1 : Create Views

public class HomeView {
public void show(){
System.out.println("Displaying Home Page");
}
}

public class StudentView {
public void show(){
System.out.println("Displaying Student Page");
}
}

Step 2 : Create 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();
}
}
}

Step 3 : Create 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) {
// log each request
trackRequest(request);

// authenticate user
if (isAuthenticUser()) {
dispatcher.dispatch(request);
}
}
}

Step 4 : Use the FrontController to demonstrate Front Controller Design Pattern

public class FrontControllerPatternDemo {
public static void main(String[] args) {
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDent");
}
}

The output will be :

Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDent
User is authenticated successfully.
Displaying Student Page

Leave a Reply

Your email address will not be published. Required fields are marked *