go语言接口适配,适配器模式
2015-12-25 16:47
1086 查看
直接上代码:
package main import "log" type LogIN interface { WARN(string) INFO(string) //其他省略 } /* 假设你写了一个框架,框架里需要打日志,具体是个什么样的日志由使用者决定 */ type Frame struct { name string log LogIN } func (f *Frame) Start() { f.log.INFO("frame start...") } //但是问题来了,使用者用了一个这样的日志库 type RealLog struct { } func (l *RealLog) warn(s string) { log.Print(s) } func (l *RealLog) info(s string) { log.Print(s) } //可以看到,真正使用的日志与框架定义的日志接口不一样,如此我们就需要适配 type AdaptLog struct { rellog *RealLog } func (alog *AdaptLog) WARN(s string) { alog.rellog.warn(s) } func (alog *AdaptLog) INFO(s string) { alog.rellog.info(s) } //有了这个适配器,我们就可以很好的在框架里使用RealLog了 func main() { adaptlog := AdaptLog{&RealLog{}} frame := Frame{name: "frame", log: &adaptlog} frame.Start() }本文出自 “viMer” 博客,请务必保留此出处http://fangnux.blog.51cto.com/7902770/1728338
相关文章推荐
- Google 新推出Background sync API
- Google 新推出Background sync API
- 如何快速地从mongo中提取数据到numpy以及pandas中去
- instance variables may not be placed in categories
- Can I change the order of items in category views?
- How to move items to another category
- How to use an FC category as Homepage / Frontpage
- Google分布式系统三驾马车: GFS,mapreduce,Bigtable
- mangos源码分析
- UVa 802 - Lead or Gold
- Go lang学习
- RockMongo安装使用笔记
- UFT12支持Goole Chrome的扩展程序
- mongo_1 新手之路
- Google 不推荐在 URL 里使用竖线
- django分页工具
- 从谷歌下载APK到电脑
- mongo常用手册
- Django1.8开发当中的异常处理
- django 模板里面for循环常用的方法