设计模式 - 前端控制器模式
设计模式 - 服务定位器模式

设计模式 - 拦截过滤器模式

violet posted @ Jul 11, 2020 06:31:59 AM in 笔记 with tags Design Pattern Golang , 386 阅读

拦截过滤器模式(Intercepting Filter Pattern)用于对应用程序的请求或响应做一些预处理/后处理。定义过滤器,并在把请求传给实际目标应用程序之前应用在请求上。过滤器可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。以下是这种设计模式的实体。

  • 过滤器(Filter) - 过滤器在请求处理程序执行请求之前或之后,执行某些任务。
  • 过滤器链(Filter Chain) - 过滤器链带有多个过滤器,并在 Target 上按照定义的顺序执行这些过滤器。
  • Target - Target 对象是请求处理程序。
  • 过滤管理器(Filter Manager) - 过滤管理器管理过滤器和过滤器链。
  • 客户端(Client) - Client 是向 Target 对象发送请求的对象。

 

package main

import "fmt"

type Filter interface {
	Execute(string)
}

type AuthenticationFilter struct{}

func (a *AuthenticationFilter) Execute(request string) {
	fmt.Println("AuthenticationFilter request: ", request)
}

type DebugFilter struct{}

func (d *DebugFilter) Execute(request string) {
	fmt.Println("DebugFilter request: ", request)
}

type Target struct{}

func (t *Target) Execute(request string) {
	fmt.Println("Executing request: ", request)
}

type FilterChain struct {
	Filters []Filter
	Target  *Target
}

func (f *FilterChain) AddFilter(filter Filter) {
	f.Filters = append(f.Filters, filter)
}

func (f *FilterChain) Execute(request string) {
	for _, f := range f.Filters {
		f.Execute(request)
	}
	f.Target.Execute(request)
}

func (f *FilterChain) SetTarget(target *Target) {
	f.Target = target
}

type FilterManager struct {
	FilterChain *FilterChain
}

func NewFilterManager(target *Target) *FilterManager {
	return &FilterManager{
		FilterChain: &FilterChain{
			Filters: []Filter{},
			Target:  target,
		},
	}
}

func (f *FilterManager) SetFilter(filter Filter) {
	f.FilterChain.AddFilter(filter)
}

func (f *FilterManager) FilterRequest(request string) {
	f.FilterChain.Execute(request)
}

type Client struct {
	FilterManager *FilterManager
}

func (c *Client) SetFilterManager(manager *FilterManager) {
	c.FilterManager = manager
}

func (c *Client) SendRequest(request string) {
	c.FilterManager.FilterRequest(request)
}

func main() {
	manager := NewFilterManager(&Target{})
	manager.SetFilter(&AuthenticationFilter{})
	manager.SetFilter(&DebugFilter{})

	client := &Client{FilterManager: manager}
	client.SendRequest("home")
}
Chennai Escorts Serv 说:
Apr 29, 2022 03:55:22 PM

I wanted to thank you for this great read!! I definitely enjoy every little bit of it. I have you bookmarked to check out the new stuff you post.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter