目录
过滤器模式(Filter/Criteria Pattern)
代码实现
过滤器模式(Filter/Criteria Pattern)
过滤器模式(Filter Pattern)或标准模式(Criteria Pattern)是一种设计模式,这种模式允许开发人员使用不同的标准来过滤一组对象,通过逻辑运算以解耦的方式把它们连接起来。这种类型的设计模式属于结构型模式,它结合多个标准来获得单一标准。可以自由组合不同的过滤条件。
代码实现
package mainimport ("fmt""log""strconv""strings"
)type Request interface {
}type Response interface {
}type Filter interface {Process(data Request) (Response, error)
}type SplitFilter struct {delimiter string
}func NewSplitFilter(delimiter string) *SplitFilter {return &SplitFilter{delimiter}
}
func (sf *SplitFilter) Process(data Request) (Response, error) {str, ok := data.(string)if !ok {return nil, fmt.Errorf("输入数据必须为String类型")}parts := strings.Split(str, sf.delimiter)return parts, nil
}type ToIntFilter struct {
}func NewToIntFilter() *ToIntFilter {return &ToIntFilter{}
}
func (ttf *ToIntFilter) Process(data Request) (Response, error) {parts, ok := data.([]string)if !ok {return nil, fmt.Errorf("输入数据必须为[]String类型")}res := make([]int, 0)for _, part := range parts {s, err := strconv.Atoi(part)if err != nil {return nil, err}res = append(res, s)}return res, nil
}type SumFilter struct {
}func NewSumFilter() *SumFilter {return &SumFilter{}
}
func (sf *SumFilter) Process(data Request) (Response, error) {elms, ok := data.([]int)if !ok {return nil, fmt.Errorf("输入数据必须为[]int类型")}ret := 0for _, elem := range elms {ret += elem}return ret, nil
}type Pipeline struct {Name stringFilters *[]Filter
}func NewPipeline(name string, filters ...Filter) *Pipeline {return &Pipeline{Name: name,Filters: &filters,}
}
func (p *Pipeline) Process(data Request) (Response, error) {var res interface{}var err errorfor _, filter := range *p.Filters {res, err = filter.Process(data)if err != nil {return res, err}data = res}return res, err
}func main() {//将字符串分割,再转成int,再求和split := NewSplitFilter(",")toInt := NewToIntFilter()sum := NewSumFilter()p := NewPipeline("p1", split, toInt, sum)res, err := p.Process("4,5,6")if err != nil {log.Fatal(err)}if res != 15 {log.Fatalf("不是预期值:%d", res)}fmt.Println(res)
}