职责链模式
定义: 将请求的发送和接受解藕,让多个接收对象都有机会处理这个请求,将这些接收对象,
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
package chain
type SensitiveWordFilter interface { Filter(content string) bool }
type SensitiveWordFilterChain struct { filters []SensitiveWordFilter }
func (c *SensitiveWordFilterChain) AddFilter(filter SensitiveWordFilter) { c.filters = append(c.filters, filter) }
func (c *SensitiveWordFilterChain) Filter(content string) bool { for _, filter := range c.filters { if filter.Filter(content) { return true } } return false }
type AdSensitiveWordFilter struct{}
func (f *AdSensitiveWordFilter) Filter(content string) bool { return false }
type PoliticalWordFilter struct{}
func (f *PoliticalWordFilter) Filter(content string) bool { return true }
|
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package chain
import ( "testing"
"github.com/stretchr/testify/assert" )
func TestSensitiveWordFilterChain_Filter(t *testing.T) { chain := &SensitiveWordFilterChain{} chain.AddFilter(&AdSensitiveWordFilter{}) assert.Equal(t, false, chain.Filter("test"))
chain.AddFilter(&PoliticalWordFilter{}) assert.Equal(t, true, chain.Filter("test")) }
|