Golang设计模式之责任链模式

Jackey Golang 2,089 次浏览 , , 没有评论

创建文件Manger.go

package chain

// 主管 经理  总经理  董事长
// 20   100   150    200
type Manger interface {
    HaveRight(money int) bool                     // 判断权限
    HandleFeeRequest(name string, money int) bool // 向后传递
}

创建文件RequestChain.go

package chain

type RequestChain struct {
    Manger
    successor *RequestChain // 处理成功
}

// 判断责任链在哪里结束
func (rc *RequestChain) SetSuccessor(endrc *RequestChain) {
    rc.successor = endrc
}

// 权利判断
func (rc *RequestChain) HaveRight(money int) bool {
    return true
}

// 向后传递,有权利当场处理,没有权利放弃,向后传递
func (rc *RequestChain) HandleFeeRequest(name string, money int) bool {
    if rc.Manger.HaveRight(money) {
        return rc.Manger.HandleFeeRequest(name, money)
    }
    if rc.successor != nil {
        return rc.successor.HandleFeeRequest(name, money)
    }
    return false
}

创建文件ProjectManger.go

package chain

import "fmt"

type ProjectManger struct {
}

func NewProjectManger() *ProjectManger {
    return &ProjectManger{}
}

func NewProjectMangerChain() *RequestChain {
    return &RequestChain{&ProjectManger{}, nil}
}

func (pm *ProjectManger) HaveRight(money int) bool {
    return money < 1000
}

func (pm *ProjectManger) HandleFeeRequest(name string, money int) bool {
    if name == "Jackey" {
        fmt.Printf("Project manger 授权 %s %d\n", name, money)
        return true
    }
    fmt.Printf("Project manger not 授权 %s %d\n", name, money)
    return false
}

创建文件DepManger.go

package chain

import "fmt"

type DepManger struct {
}

func NewDepManger() *DepManger {
    return &DepManger{}
}

func NewDepMangerChain() *RequestChain {
    return &RequestChain{&DepManger{}, nil}
}

func (dm *DepManger) HaveRight(money int) bool {
    return money < 5000
}

func (dm *DepManger) HandleFeeRequest(name string, money int) bool {
    if name == "Jackey" {
        fmt.Printf("dep manger 授权 %s %d\n", name, money)
        return true
    }
    fmt.Printf("dep manger not 授权 %s %d\n", name, money)
    return false
}

创建文件GeneralManger.go

package chain

import "fmt"

type GeneralManger struct {
}

func NewGeneralManger() *GeneralManger {
    return &GeneralManger{}
}

func NewGeneralMangerChain() *RequestChain {
    return &RequestChain{&GeneralManger{}, nil}
}

func (gm *GeneralManger) HaveRight(money int) bool {
    return true
}

func (gm *GeneralManger) HandleFeeRequest(name string, money int) bool {
    if name == "Jackey" {
        fmt.Printf("general manger 授权 %s %d\n", name, money)
        return true
    }
    fmt.Printf("general manger not 授权 %s %d\n", name, money)
    return false
}

main.go

package main

import "test/design/chain"

func main() {
    c1 := chain.NewProjectMangerChain()
    c2 := chain.NewDepMangerChain()
    c3 := chain.NewGeneralMangerChain()

    c1.SetSuccessor(c2)
    c2.SetSuccessor(c3)

    var c chain.Manger = c1
    c.HandleFeeRequest("Jackey", 1500)
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go