责任链-当电流失败时如何调用特定处理程序

时间:2019-03-25 13:54:35

标签: go chain-of-responsibility

我将使用Chain of responsibility pattern进行简单的CLI对话框:

type Handler interface {
    Request(flag bool)
}

type AskName struct {
    next Handler
}

func (h *AskName) Request(flag bool) {
    fmt.Println("AskName.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type AskAge struct {
    next Handler
}

func (h *AskAge) Request(flag bool) {
    fmt.Println("AskAge.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type AskEmail struct {
    next Handler
}

func (h *AskEmail) Request(flag bool) {
    fmt.Println("AskEmail.Request()")
}

func main() {
    handlerA := &AskName{&AskAge{new(AskEmail)}}
    handlerA.Request(true)
}

问题:设想一下用户输入无效电子邮件时的情况。如何重新调用AskEmail处理程序(或完全调用其他处理程序)?

例如,如果我这样分割逻辑:

type AskEmail struct {
    next Handler
}

func (h *AskEmail) Request(flag bool) {
    fmt.Println("AskEmail.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type ValidateEmail struct {
    next Handler
}

func (h *ValidateEmail) Request(flag bool) {
    fmt.Println("ValidateEmail.Request()")
}

如果AskEmail失败,如何从ValidateEmail呼叫ValidateEmail

2 个答案:

答案 0 :(得分:1)

我想你可以做到

type AskEmail struct {
    next Handler
}

func (h *AskEmail) Request(flag bool) {
    fmt.Println("AskEmail.Request()")
    if flag {
        h.next.Request(flag)
    }
}

type ValidateEmail struct {
    next Handler
    prev Handler
}

func (h *ValidateEmail) Request(flag bool) {
    fmt.Println("ValidateEmail.Request()")
    if !valid {
       h.prev.Request(flag)
    }
}

askEmail := &AskEmail{}
validateEmail := &ValidateEmail{prev: askEmail}
askEmail.next = validateEmail

答案 1 :(得分:1)

  

想象的情况,当用户输入无效的电子邮件时。如何重新调用AskEmail处理程序(或完全调用其他处理程序)?

我认为,除非链中的AskEmail“链接”取回有效的电子邮件地址,否则不应调用next。如果每个“链接”都已处理好自己的职责,则仅应调用next-如果同时查看https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern#UML_class_and_sequence_diagramhttps://refactoring.guru/design-patterns/chain-of-responsibility,您将看到控制权仅朝一个方向传播。

https://github.com/yksz/go-design-patterns/blob/master/behavior/chain_of_responsibility.go处的示例有点简单

如果您遵循这个想法,您的代码将变成这样:

func main() {
    // Build a chain of steps to take
    c := AskEmail{
        next: AskName{
            next: Print{},
        },
    }

    //  Run the chain with an empty "Person"
    c.Run(&Person{})
}

// Person holds the data that is relevant to your application. It should have a name that makes sense for your domain
type Person struct {
    Email string
    Name string
}

// PersonInfoChainLink is a link in the chain of command
type PersonInfoChainLink interface {
    Run(p *Person) (error)
}

// AskEmail can ask for an e-mail address
type AskEmail struct {
    next PersonInfoChainLink
}

func (a AskEmail) Run(p *Person) (error) {

    // Ask for e-mail addresses until the user gives a valid one
    var err error
    var email string
    for {
        email, err = askString(`What is your e-mail address?`)
        if err != nil {
            return err
        }

        if strings.Contains(email, `@`) {
            break
        }

        fmt.Printf("Invalid e-mail address %s!", email)

    }
    p.Email = email

    return a.next.Run(p)
}

// AskName can ask for the name of a person
type AskName struct {
    next PersonInfoChainLink
}

func (a AskName) Run(p *Person) (error) {
    name, err := askString(`What is your name?`)
    if err != nil {
        return err
    }
    p.Name = name
    return a.next.Run(p)
}

// Print can print the information about a person
type Print struct {

}

func (Print) Run(p *Person) (error) {
    log.Printf(`Email %s at %s!`, p.Name, p.Email)
    return nil
}

func askString(question string) (string, error) {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print(question + ` `)
    return reader.ReadString('\n')
}