前端控制器模式(Front Controller Pattern)是用來(lái)提供一個(gè)集中的請(qǐng)求處理機(jī)制,所有的請(qǐng)求都將由一個(gè)單一的處理程序處理。該處理程序可以做認(rèn)證/授權(quán)/記錄日志,或者跟蹤請(qǐng)求,然后把請(qǐng)求傳給相應(yīng)的處理程序。以下是這種設(shè)計(jì)模式的實(shí)體。
- 前端控制器(Front Controller) - 處理應(yīng)用程序所有類型請(qǐng)求的單個(gè)處理程序,應(yīng)用程序可以是基于 web 的應(yīng)用程序,也可以是基于桌面的應(yīng)用程序。
- 調(diào)度器(Dispatcher) - 前端控制器可能使用一個(gè)調(diào)度器對(duì)象來(lái)調(diào)度請(qǐng)求到相應(yīng)的具體處理程序。
- 視圖(View) - 視圖是為請(qǐng)求而創(chuàng)建的對(duì)象。
- 創(chuàng)建視圖。
/**
* 1. 創(chuàng)建視圖。
* @author mazaiting
*/
public class HomeView {
public void show() {
System.out.println("Displaying Home Page");
}
}
/**
* 1. 創(chuàng)建視圖
* @author mazaiting
*/
public class StudentView {
public void show() {
System.out.println("Displaying Student Page");
}
}
- 創(chuàng)建調(diào)度器 Dispatcher。
/**
* 2. 創(chuàng)建調(diào)度器 Dispatcher。
* @author mazaiting
*/
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();
}
}
}
- 創(chuàng)建前端控制器 FrontController。
/**
* 3. 創(chuàng)建前端控制器 FrontController。
* @author mazaiting
*/
public class FrontController {
private Dispatcher dispatcher;
public FrontController() {
dispatcher = new Dispatcher();
}
/**
* 是否驗(yàn)證用戶
*/
private boolean isAuthenticUser(){
System.out.println("User is authenticated successfully.");
return true;
}
/**
* 記錄請(qǐng)求
*/
private void trackRequest(String request){
System.out.println("Page requested: " + request);
}
/**
* 分發(fā)請(qǐng)求
*/
public void dispatchRequest(String request){
// 記錄每一個(gè)請(qǐng)求
trackRequest(request);
// 對(duì)用戶進(jìn)行身份驗(yàn)證
if (isAuthenticUser()) {
dispatcher.dispatch(request);
}
}
}
- 使用 FrontController 來(lái)演示前端控制器設(shè)計(jì)模式。
/**
* 4. 使用 FrontController 來(lái)演示前端控制器設(shè)計(jì)模式。
* @author mazaiting
*/
public class Client {
public static void main(String[] args) {
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
}
- 打印結(jié)果
Page requested: HOME
User is authenticated successfully.
Displaying Home Page
Page requested: STUDENT
User is authenticated successfully.
Displaying Student Page