实例
我们将创建一个FrontController和Dispatcher分别充当Front Controller和Dispatcher。HomeView和StudentView代表可以向前端控制器提出请求的各种视图。
我们的演示类 FrontControllerPatternDemo,将使用FrontController证明前端控制器设计模式。
第1步 - 创建视图。 HomeView.java , StudentView.java
public class HomeView {
public void show(){
System.out.println("Displaying Home Page");
}
}
public class StudentView {
public void show(){
System.out.println("Displaying Student Page");
}
}
第2步 - 创建分派器。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();
}
}
}
第3步 - 创建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){
//log each request
trackRequest(request);
//authenticate the user
if(isAuthenticUser()){
dispatcher.dispatch(request);
}
}
}
步骤4 - 使用FrontController演示前端控制器设计模式。FrontControllerPatternDemo.java
public class FrontControllerPatternDemo {
public static void main(String[] args) {
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
}
第5步 - 验证输出。
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page