Leetcode - 前端控制器模式
前端控制器模式(Front Controller Pattern)是用來提供一個集中的請求處理機制,所有的請求都將由一個單一的處理程序處理。該處理程序可以做認證/授權/記錄日誌,或者跟蹤請求,然後把請求傳給相應的處理程序。以下是這種設計模式的實體。
- 前端控制器(Front Controller) - 處理應用程序所有類型請求的單個處理程序,應用程序可以是基於 web 的應用程序,也可以是基於桌面的應用程序。
- 調度器(Dispatcher) - 前端控制器可能使用一個調度器對象來調度請求到相應的具體處理程序。
- 視圖(View) - 視圖是爲請求而創建的對象。
package main import "fmt" type HomeView struct{} func (h *HomeView) Show() { fmt.Println("displaying home page") } type StudentView struct{} func (s *StudentView) Show() { fmt.Println("displaying student page") } type Dispatcher struct { HomeView *HomeView StudentView *StudentView } func NewDispatcher() *Dispatcher { return &Dispatcher{ HomeView: &HomeView{}, StudentView: &StudentView{}, } } func (d *Dispatcher) Dispatch(request string) { if request == "student" { d.StudentView.Show() } else { d.HomeView.Show() } } type FrontController struct { Dispatcher *Dispatcher } func NewFrontController() *FrontController { return &FrontController{ Dispatcher: NewDispatcher(), } } func (f *FrontController) isAuthenticUser() bool { fmt.Println("user is authenticated successfully") return true } func (f *FrontController) trackRequest(request string) { fmt.Println("Page requested: ", request) } func (f *FrontController) DispatherRequest(request string) { f.trackRequest(request) if f.isAuthenticUser() { f.Dispatcher.Dispatch(request) } } func main() { controller := NewFrontController() controller.DispatherRequest("home") controller.DispatherRequest("student") }