ChainOfResponsibility.go
package ChainOfResponsibility

import (
	"fmt"
	"io"
	"strings"
)

type ChainLogger interface {
	Next(string)
}

type FirstLogger struct {
	NextChain ChainLogger
}

func (f *FirstLogger) Next(s string) {
	fmt.Printf("First logger: %s\n", s)

	if f.NextChain != nil {
		f.NextChain.Next(s)
	}
}

type SecondLogger struct {
	NextChain ChainLogger
}

func (se *SecondLogger) Next(s string) {
	if strings.Contains(strings.ToLower(s), "hello") {
		fmt.Printf("Second logger: %s\n", s)

		if se.NextChain != nil {
			se.NextChain.Next(s)
		}
		return
	}
	fmt.Printf("Finishing in second logging\n\n")
}

type WriterLogger struct {
	NextChain ChainLogger
	Writer    io.Writer
}

func (w *WriterLogger) Next(s string) {
	if w.Writer != nil {
		w.Writer.Write([]byte("WriterLogger: " + s))
	}
	if w.NextChain != nil {
		w.NextChain.Next(s)
	}
}

  

ChainOfResponsibility_test.go
package ChainOfResponsibility

import (
	"fmt"
	"strings"
	"testing"
)

type myTestWriter struct {
	receivedMessage *string
}

func (m *myTestWriter) Write(p []byte) (int, error) {
	if m.receivedMessage == nil {
		m.receivedMessage = new(string)
	}
	tempMessage := fmt.Sprintf("%p%s", m.receivedMessage, p)
	m.receivedMessage = &tempMessage
	return len(p), nil
}

func (m *myTestWriter) Next(s string) {
	m.Write([]byte(s))
}

func TestCreateDefaultChain(t *testing.T) {
	myWriter := myTestWriter{}

	writerLogger := WriterLogger{Writer: &myWriter}
	second := SecondLogger{NextChain: &writerLogger}
	chain := FirstLogger{NextChain: &second}

	t.Run("3 loggers, 2 of them writes to console, second only if it founds"+
		"the world 'hello', third writes to some variable if second found 'hello'",
		func(t *testing.T) {
			chain.Next("message that breaks the chain\n")

			if myWriter.receivedMessage != nil {
				t.Error("Last link should not receive any message")
			}

			chain.Next("Hello\n")
			if *myWriter.receivedMessage == "" ||
				!strings.Contains(*myWriter.receivedMessage, "Hello") {
				t.Fatal("Last link did not received expected message")
			}
		})
}

  

												

最新文章

  1. 分布式集群系统下的高可用session解决方案
  2. UTF-8 ->GBK
  3. POJ3635 Full Tank?(DP + Dijkstra)
  4. gfortran编译Fortran数组问题
  5. Java文件操作①——XML文件的读取
  6. pb中创建连接webservice对象实例方法
  7. CSS3- px、em、rem区别介绍
  8. ASP.NET MVC @helper使用说明
  9. 安卓从业者应该关注:Android 6.0的运行时权限
  10. Presto: 可以处理PB级别数据的分布式SQL查询引擎
  11. Red5 配置RTMPT
  12. 教你爱上Blocks(闭包)
  13. shell丢弃信息
  14. vue-axios的application/x-www-form-urlencod的post请求无法解析参数
  15. 【C#】Using的一个比较好的语言文字解释
  16. 2017-2018-2 20165228 实验二《Java面向对象程序设计》实验报告
  17. python xml.etree.ElementTree模块
  18. cxf 相关问题
  19. java学习笔记-JavaWeb篇一
  20. Python全栈开发之2、运算符与基本数据结构

热门文章

  1. 洛谷P5364 [SNOI2017]礼物 题解
  2. tf.nn.in_top_k的用法
  3. JVM常用参数详解
  4. How to: Use XPO Upcasting in XAF 如何:在 XAF 中使用 XPO 强制转换
  5. 《Vue笔记01: 我与唐金州二三事》
  6. English:Day-to-day 1014
  7. Spring Cloud 如何搭建Config
  8. Linux & Go & Vscode & 插件
  9. UTXO和Account模型一个都不能少
  10. 函数式接口 & lambda表达式 & 方法引用