Friday 30 August 2013

Front Controller Design Pattern - Implementation


Click here to watch in Youtube : https://www.youtube.com/watch?v=NWNNsbMsrq4

Click the below Image to Enlarge
Front Controller Design Pattern - Implementation - Class Diagram























UserView.java

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


SalaryView.java

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


AccountView.java

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

Dispatcher.java

public class Dispatcher
{
private SalaryView  salaryView;
private UserView    userView;
private AccountView accountView;

public Dispatcher()
{
salaryView = new SalaryView();
userView = new UserView();
accountView = new AccountView();
}

public void dispatch( String request )
{
if( request.equalsIgnoreCase("USER") )
{
userView.show();
}
else if( request.equalsIgnoreCase("ACCOUNT") )
{
accountView.show();
}
else
{
salaryView.show();
}
}
}


FrontController.java

public class FrontController
{
private Dispatcher dispatcher;

public FrontController()
{
dispatcher = new Dispatcher();
}

private boolean isAuthenticUser()
{
//here you have to write Authentication logic
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);
}
}
}

FrontControllerPatternDemo.java

public class FrontControllerPatternDemo
{
public static void main( String[] args )
{
FrontController frontController = new FrontController();
frontController.dispatchRequest("USER");
System.out.println();
frontController.dispatchRequest("ACCOUNT");
System.out.println();
frontController.dispatchRequest("SALARY");
}
}

Output

Page requested: USER
User is authenticated successfully.
Displaying User Page

Page requested: ACCOUNT
User is authenticated successfully.
Displaying Account Page

Page requested: SALARY
User is authenticated successfully.
Displaying Salary Page


See also:

  • Front Controller Design Pattern - Introduction
  • Front Controller Design Pattern - Class and Sequence Diagram
  • Front Controller Design Pattern - Key Points
  • All Design Patterns Links



  • No comments:

    Post a Comment