Design Pattern 简明教程
Design Pattern - Front Controller Pattern
前端控制器设计模式用于提供集中式请求处理机制,以便所有请求都由单个处理程序处理。此处理程序可以执行身份验证/授权/请求日志记录或跟踪,然后将请求传递到相应的处理程序。以下是这种设计模式的实体。
The 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 type of design pattern.
-
Front Controller - Single handler for all kinds of requests coming to the application (either web based/ 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.
Implementation
我们将创建一个 FrontController 和 Dispatcher 分别充当 Front Controller 和 Dispatcher。HomeView 和 StudentView 表示各种视图,前端控制器可以针对这些视图接收请求。
We are going to create a FrontController and Dispatcher to act as Front Controller and Dispatcher correspondingly. HomeView and StudentView represent various views for which requests can come to front controller.
我们的演示类 FrontControllerPatternDemo 将使用 FrontController 来演示前端控制器设计模式。
FrontControllerPatternDemo, our demo class, will use FrontController to demonstrate 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 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 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);
}
}
}
Step 4
使用前端控制器演示前端控制器设计模式。
Use the FrontController to demonstrate 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");
}
}