go语言设计模式之Chain Of Responsibility(责任链)
2024-10-04 10:29:49
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") } }) }
最新文章
- 分布式集群系统下的高可用session解决方案
- UTF-8 ->;GBK
- POJ3635 Full Tank?(DP + Dijkstra)
- gfortran编译Fortran数组问题
- Java文件操作①——XML文件的读取
- pb中创建连接webservice对象实例方法
- CSS3- px、em、rem区别介绍
- ASP.NET MVC @helper使用说明
- 安卓从业者应该关注:Android 6.0的运行时权限
- Presto: 可以处理PB级别数据的分布式SQL查询引擎
- Red5 配置RTMPT
- 教你爱上Blocks(闭包)
- shell丢弃信息
- vue-axios的application/x-www-form-urlencod的post请求无法解析参数
- 【C#】Using的一个比较好的语言文字解释
- 2017-2018-2 20165228 实验二《Java面向对象程序设计》实验报告
- python xml.etree.ElementTree模块
- cxf 相关问题
- java学习笔记-JavaWeb篇一
- Python全栈开发之2、运算符与基本数据结构
热门文章
- 洛谷P5364 [SNOI2017]礼物 题解
- tf.nn.in_top_k的用法
- JVM常用参数详解
- How to: Use XPO Upcasting in XAF 如何:在 XAF 中使用 XPO 强制转换
- 《Vue笔记01: 我与唐金州二三事》
- English:Day-to-day 1014
- Spring Cloud 如何搭建Config
- Linux &; Go &; Vscode &; 插件
- UTXO和Account模型一个都不能少
- 函数式接口 &; lambda表达式 &; 方法引用