Leetcode - 前端控制器模式

栏目: IT技术 · 发布时间: 5年前

内容简介:前端控制器模式(Front Controller Pattern)是用来提供一个集中的请求处理机制,所有的请求都将由一个单一的处理程序处理。该处理程序可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体。

前端控制器模式(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")
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

程序设计实践

程序设计实践

[美] Brian W. Kernighan、Rob Pike / 裘宗燕 / 机械工业出版社 / 2000-8 / 20.00元

这本书从排错、测试、性能、可移植性、设计、界面、风格和记法等方面,讨论了程序设计中实际的、又是非常深刻和具有广泛意义的思想、技术和方法。一起来看看 《程序设计实践》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具