go责任链模式

package main

import (
	"context"

	"log"
)

// 需要处理的请求数据
type Request struct {
	Ctx context.Context
	Id  int
}

// 定义处理器接口
type Handler interface {
	Process(req Request) bool
	SetNext(handler Handler)
}

// 创建具体处理器
type HandlerFirst struct {
	next Handler
}

func (h *HandlerFirst) Process(req Request) bool {
	if h.next != nil {
		log.Printf("handlerFirst process")
		return h.next.Process(req)
	}
	log.Printf("HandlerFirst not process")
	return false
}

func (h *HandlerFirst) SetNext(handler Handler) {
	h.next = handler
}

type HandlerSecond struct {
	next Handler
}

func (h *HandlerSecond) Process(req Request) bool {
	if h.next != nil {
		log.Printf("HandlerSecond process")
		return h.next.Process(req)
	}
	log.Printf("HandlerSecond not process")
	return false
}

func (h *HandlerSecond) SetNext(handler Handler) {
	h.next = handler
}

type HandlerThird struct {
	next Handler
}

func (h *HandlerThird) Process(req Request) bool {
	log.Printf("HandlerThird process")
	return true
}

func (h *HandlerThird) SetNext(handler Handler) {
	h.next = handler
}

// 构建责任链
func CreateApprovalChain() Handler {
	first := &HandlerFirst{}
	second := &HandlerSecond{}
	third := &HandlerThird{}
	first.SetNext(second)
	second.SetNext(third)
	return first
}
func CreateApprovalChain2() Handler {
	first := &HandlerFirst{}
	second := &HandlerSecond{}
	third := &HandlerThird{}
	second.SetNext(first)
	first.SetNext(third)
	return second
}

func main() {
	chain := CreateApprovalChain()

	req := Request{Ctx: nil, Id: 1}
	result := chain.Process(req)

	log.Printf("最终审批结果:%v", result)

	chain1 := CreateApprovalChain2()
	req1 := Request{Ctx: nil, Id: 1}
	result1 := chain1.Process(req1)

	log.Printf("最终审批结果:%v", result1)

}

posted @ 2025-04-17 16:20  cn_zt  阅读(23)  评论(0)    收藏  举报