Chain of Responsibility (Chain of Responsibility)

Chain of Responsibility (Chain of Responsibility)

1. Intention

Give multiple objects the opportunity to process the request, thereby avoiding the coupling relationship between the sender and receiver of the request. Connect these objects into a chain and pass the request along this chain until an object handles it.

2. Applicability

Use the Responsibility chain under the following conditions:

  • There are multiple objects that can handle a request, and which object handles the request is automatically determined at runtime.
  • You want to submit a request to one of multiple objects without explicitly specifying the recipient.
  • The collection of objects that can handle a request should be dynamically specified.

3. Structure

Insert picture description here

A typical object structure might look like the following figure:

Insert picture description here

4. Code

package chain

import (
	"fmt"
	"strings"
	"testing"
)

/*
# 职责链模式

职责链模式用于分离不同职责,并且动态组合相关职责。
Golang实现职责链模式时候,因为没有继承的支持,使用链对象包涵职责的方式,即:
* 链对象包含当前职责对象以及下一个职责链。
* 职责对象提供接口表示是否能处理对应请求。
* 职责对象提供处理函数处理相关职责。
同时可在职责链类中实现职责接口相关函数,使职责链对象可以当做一般职责对象是用。
 */

type Msg struct {
    
    
	data string
}

type Filter interface {
    
    
	DoFilter(*Msg) bool
}

type filterChain struct {
    
    
	filters  []Filter
}

func NewFilterChain()*filterChain{
    
    
	return &filterChain{
    
    
		filters: make([]Filter,0),
	}
}

func (this *filterChain)Add(filter Filter) *filterChain{
    
    
	this.filters=append(this.filters, filter)
	return this
}

func (this *filterChain)DoFilter(msg *Msg)bool{
    
    
	for _,v:=range this.filters {
    
    
		r:=v.DoFilter(msg)
		if !r{
    
    
			return false
		}
	}
	return true
}



// 广告过滤
type AdHandler struct {
    
    
	Filter
}
func (this *AdHandler) DoFilter(msg *Msg) bool {
    
    
	fmt.Println("执行广告过滤。。。")
	msg.data = strings.ReplaceAll(msg.data, "广告", "**")
	return true
}

// 涉黄过滤
type YellowHandler struct {
    
    
	Filter
}
func (this *YellowHandler) DoFilter(msg *Msg) bool {
    
    
	fmt.Println("执行涉黄过滤。。。")
	msg.data = strings.ReplaceAll(msg.data, "涉黄", "**")
	return true
}

// 敏感词过滤
type SensitiveHandler struct {
    
    
	Filter
}
func (this *SensitiveHandler) DoFilter(msg *Msg) bool {
    
    
	fmt.Println("执行敏感词过滤。。。")
	msg.data = strings.ReplaceAll(msg.data, "敏感词", "***")
	return true
}


func TestCOR(t *testing.T){
    
    
	msg:=&Msg{
    
    "我是正常内容,我是广告,我是涉黄,我是敏感词,我是正常内容"}
	rs:=NewFilterChain().
		Add(&AdHandler{
    
    }).
		Add(NewFilterChain().
			Add(&SensitiveHandler{
    
    })).
		Add(&YellowHandler{
    
    }).
		DoFilter(msg)
	fmt.Println(rs,msg.data)
}

Guess you like

Origin blog.csdn.net/dawnto/article/details/112973920