责任链模式(Chain of Responsibility)

责任链模式(Chain of Responsibility)

1.意图

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

2.适用性

在以下条件下使用Responsibility链:

  • 有多个的对象可以处理一个请求,哪个对象处理该请求运行时刻自动确定。
  • 你想在不明确指定接收者的情况下,向多个对象中的一个提交一个请求。
  • 可处理一个请求的对象集合应被动态指定。

3.结构

在这里插入图片描述

一个典型的对象结构可能如下图所示:

在这里插入图片描述

4.代码

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)
}

猜你喜欢

转载自blog.csdn.net/dawnto/article/details/112973920