go语言设计模式之visitor

Posted aguncn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言设计模式之visitor相关的知识,希望对你有一定的参考价值。

这个确实没有调通,也要记录一下

visitor.go

package visitor

import (
	"fmt"
	"io"
	"os"
)

type MessageA struct {
	Msg    string
	Output io.Writer
}

func (m *MessageA) Accept(v Visitor) {
	//nothing
	v.VisitA(m)
}

func (m *MessageA) Print() {
	//nothing
	if m.Output == nil {
		m.Output = os.Stdout
	}
	fmt.Printf("A: %s
", m.Msg)
	fmt.Fprintf(m.Output, "A: %s", m.Msg)
}

type MessageB struct {
	Msg    string
	Output io.Writer
}

func (m *MessageB) Accept(v Visitor) {
	//nothing
	v.VisitB(m)
}

func (m *MessageB) Print() {
	//nothing
	if m.Output == nil {
		m.Output = os.Stdout
	}
	fmt.Printf("B: %s
", m.Msg)
	fmt.Fprintf(m.Output, "B: %s", m.Msg)
}

type Visitor interface {
	VisitA(*MessageA)
	VisitB(*MessageB)
}

type Visitable interface {
	Accept(Visitor)
}

type MessageVisitor struct{}

func (mf *MessageVisitor) VisitA(m *MessageA) {
	//nothing
	m.Msg = fmt.Sprintf("%s %s", m.Msg, "(Visited A)")
}

func (mf *MessageVisitor) VisitB(m *MessageB) {
	//nothing
	m.Msg = fmt.Sprintf("%s %s", m.Msg, "(Visited B)")
}

  

visitor_test.go

package visitor

import (
	"fmt"
	"testing"
)

type TestHelper struct {
	Received string
}

func (t TestHelper) Write(p []byte) (int, error) {
	t.Received = string(p)
	return len(p), nil
}

func Test_Overall(t *testing.T) {
	testHelper := &TestHelper{}
	visitor := &MessageVisitor{}

	t.Run("MessageA test", func(t *testing.T) {
		msg := MessageA{
			Msg:    "Hello World",
			Output: testHelper,
		}

		msg.Accept(visitor)
		msg.Print()

		fmt.Print(testHelper)

		expected := "A: Hello World (Visited A)"
		if testHelper.Received != expected {
			t.Errorf("Expected result was incorrect. %s != %s", testHelper.Received, expected)
		}
	})

	t.Run("MessageB test", func(t *testing.T) {
		msg := MessageB{
			Msg:    "Hello World",
			Output: testHelper,
		}

		msg.Accept(visitor)
		msg.Print()

		expected := "B: Hello World (Visited B)"
		if testHelper.Received != expected {
			t.Errorf("Expected result was incorrect. %s != %s", testHelper.Received, expected)
		}
	})
}

  技术图片

以上是关于go语言设计模式之visitor的主要内容,如果未能解决你的问题,请参考以下文章

编程模式之Go语言如何实现装饰器

Go语言设计模式之函数式选项模式

设计模式之Visitor模式(笔记)

设计模式入门之訪问者模式Visitor

Java语言基础之方法的设计

设计模式---行为变化模式之访问器模式(Visitor)