前端控制器模式(Front Controller Pattern)是用來提供一個集中的請求處理機(jī)制博脑,所有的請求都將由一個單一的處理程序處理。該處理程序可以做認(rèn)證/授權(quán)/記錄日志炭玫,或者跟蹤請求,然后把請求傳給相應(yīng)的處理程序貌虾。以下是這種設(shè)計模式的實體吞加。
前端控制器(Front Controller)?- 處理應(yīng)用程序所有類型請求的單個處理程序,應(yīng)用程序可以是基于 web 的應(yīng)用程序,也可以是基于桌面的應(yīng)用程序衔憨。
調(diào)度器(Dispatcher)?- 前端控制器可能使用一個調(diào)度器對象來調(diào)度請求到相應(yīng)的具體處理程序叶圃。
視圖(View)?- 視圖是為請求而創(chuàng)建的對象。
實現(xiàn)
我們將創(chuàng)建?FrontController践图、Dispatcher?分別當(dāng)作前端控制器和調(diào)度器掺冠。HomeView?和?StudentView?表示各種為前端控制器接收到的請求而創(chuàng)建的視圖。
FrontControllerPatternDemo码党,我們的演示類使用?FrontController?來演示前端控制器設(shè)計模式德崭。
步驟 1
創(chuàng)建視圖。
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");
? }
}
步驟 2
創(chuàng)建調(diào)度器 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();
? ? ? }?
? }
}
步驟 3
創(chuàng)建前端控制器 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){
? ? ? //記錄每一個請求
? ? ? trackRequest(request);
? ? ? //對用戶進(jìn)行身份驗證
? ? ? if(isAuthenticUser()){
? ? ? ? dispatcher.dispatch(request);
? ? ? }?
? }
}
步驟 4
使用?FrontController?來演示前端控制器設(shè)計模式。
FrontControllerPatternDemo.java
public class FrontControllerPatternDemo {
? public static void main(String[] args) {
? ? ? FrontController frontController = new FrontController();
? ? ? frontController.dispatchRequest("HOME");
? ? ? frontController.dispatchRequest("STUDENT");
? }
}
步驟 5
執(zhí)行程序兽狭,輸出結(jié)果:
Page requested: HOMEUser is authenticated successfully.Displaying Home PagePage requested: STUDENTUser is authenticated successfully.Displaying Student Page
本文轉(zhuǎn)載:https://www.runoob.com/design-pattern/design-pattern-intro.html