《大话设计模式-Golang》责任链模式

概念

责任链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,指导有一个对象处理它为止。

需求

利用责任链模式实现小菜请求加薪

UML图

《大话设计模式-Golang》责任链模式_第1张图片

代码

抽象管理者类

type IManager interface {
	RequestApplication(request Request)
	SetSuperior(manager IManager)
}

管理者类

package chainOfResponsibility

import "fmt"

type CommonManager struct {
	Name     string
	Superior IManager
}

func (c *CommonManager) RequestApplication(request Request) {
	if request.RequestType == "请假" && request.Number < 2 {
		fmt.Printf("%v : %v 数量:%v 被批准了\n", c.Name, request.RequestContext, request.Number)
	} else if c.Superior != nil {
		c.Superior.RequestApplication(request)
	}
}

func (c *CommonManager) SetSuperior(manager IManager) {
	c.Superior = manager
}

type Majordomo struct {
	Name     string
	Superior IManager
}

func (m *Majordomo) RequestApplication(request Request) {
	if request.RequestType == "请假" && request.Number <= 5 {
		fmt.Printf("%v : %v 数量:%v 被批准了\n", m.Name, request.RequestContext, request.Number)
	} else if m.Superior != nil {
		m.Superior.RequestApplication(request)
	}
}

func (m *Majordomo) SetSuperior(manager IManager) {
	m.Superior = manager
}

type GeneralManager struct {
	Name     string
	Superior IManager
}

func (g *GeneralManager) RequestApplication(request Request) {
	if request.RequestType == "请假" {
		fmt.Printf("%v : %v 数量:%v 被批准了\n", g.Name, request.RequestContext, request.Number)
	} else if request.RequestType == "加薪" && request.Number <= 500 {
		fmt.Printf("%v : %v 数量:%v 被批准了\n", g.Name, request.RequestContext, request.Number)
	} else if request.RequestType == "加薪" && request.Number > 500 {
		fmt.Printf("%v : %v 数量:%v 再说吧\n", g.Name, request.RequestContext, request.Number)
	}
}

func (g *GeneralManager) SetSuperior(manager IManager) {
	g.Superior = manager
}

请求类

type Request struct {
	RequestType    string
	RequestContext string
	Number         int
}

测试

//责任链模式
jingli := chainOfResponsibility.CommonManager{Name: "金利"}
zongjian := chainOfResponsibility.Majordomo{Name: "宗剑"}
zhongjingli := chainOfResponsibility.GeneralManager{Name: "钟精励"}
jingli.SetSuperior(&zongjian)
zongjian.SetSuperior(&zhongjingli)

request := chainOfResponsibility.Request{RequestType: "请假", RequestContext: "小菜请假", Number: 1}
jingli.RequestApplication(request)

request2 := chainOfResponsibility.Request{RequestType: "请假", RequestContext: "小菜请假", Number: 2}
jingli.RequestApplication(request2)

request3 := chainOfResponsibility.Request{RequestType: "加薪", RequestContext: "小菜请求加薪", Number: 500}
jingli.RequestApplication(request3)

request4 := chainOfResponsibility.Request{RequestType: "加薪", RequestContext: "小菜请求加薪", Number: 1000}
jingli.RequestApplication(request4)

你可能感兴趣的:(设计模式,设计模式,golang,责任链模式)