码迷,mamicode.com
首页 > 编程语言 > 详细

go语言设计模式之visitor

时间:2019-11-23 12:49:13      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:write   mic   res   pac   png   pre   err   技术   没有   

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

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\n", 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\n", 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

标签:write   mic   res   pac   png   pre   err   技术   没有   

原文地址:https://www.cnblogs.com/aguncn/p/11916909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!