【寒江雪】Go实现装饰者模式
2018-03-13 00:58
1066 查看
Decorator Pattern
装饰着模式可以在需要扩展某个类的时候,动态地修改而不需要在内部添加代码,也可以防止类爆炸。装饰者模式可以提供了灵活地扩展方案.
实现
实现一个日志的自定义功能.package decorator import ( "time" "fmt" ) type LogDecorate interface { Info() string } type LogBody struct { Msg string } func (this LogBody) Info() string { return this.Msg } type LogTimeField struct { dec LogDecorate } func (this *LogTimeField) Info() string { return time.Now().Format("[2006-1-2 15:04:05]") + this.dec.Info() } func NewLogTimeField(decorate LogDecorate)*LogTimeField{ return &LogTimeField{decorate} } type LogNameField struct { dec LogDecorate name string } func (this *LogNameField) Info() string { return this.name + ":" + this.dec.Info() } func NewLogNameField(name string,decorate LogDecorate)*LogNameField{ return &LogNameField{decorate,name} } func Log(msg string,name string){ var log LogDecorate log = LogBody{msg} log = NewLogTimeField(log) if name!=""{ log = NewLogNameField(name,log) } fmt.Println(log.Info()) }
使用
func main(){ decorator.Log("Yeah","WWT") }
另一种实现形式
不过这次不是日志了.package decorator type DecoratorFunc func(float64)float64 func DecFunc(dec DecoratorFunc)DecoratorFunc{ return func(f float64) float64 { result := dec(f) return result } }
package main func Double(decoratorFunc decorator.DecoratorFunc)decorator.DecoratorFunc{ return func(f float64) float64 { var result float64 = f if decoratorFunc!=nil { result = decoratorFunc(f) } return result*2 } } func Sqrt(decoratorFunc decorator.DecoratorFunc)decorator.DecoratorFunc{ return func(f float64) float64{ var result float64 = f if decoratorFunc!=nil { result = decoratorFunc(f) } return math.Sqrt(result) } } func main(){ f := decorator.DecFunc(Double(Sqrt(nil))) fmt.Println(f(16.0)) }
注意
装饰者模式是通过注入的方式来装饰被装饰对象的。装着模式不会修改被装饰对象的接口。
有钱的捧个钱场,没钱的捧个人场。
出来混不容易。
相关文章推荐
- 【寒江雪】Go实现策略模式
- 【寒江雪】Go实现观察者模式
- 【寒江雪】Go实现代理模式
- 【寒江雪】Go实现中介者模式
- 【寒江雪】Go实现工厂模式
- 【寒江雪】Go实现单例模式
- 【寒江雪】Go实现外观模式
- 【寒江雪】Go实现状态模式
- 【寒江雪】Go实现命令模式
- 【寒江雪】Go实现对象池模式
- 【寒江雪】Go实现组合模式
- 【寒江雪】Go实现桥接模式
- 【寒江雪】Go实现模版方法模式
- 大话设计模式--装饰者模式 Decorator -- C++实现实例
- Decorate(装饰者模式) 实现留言反馈板文本处理
- go语言实现设计模式(一):策略模式
- 最常用的设计模式---装饰者模式(C++实现)
- Java基于装饰者模式实现的图片工具类实例【附demo源码下载】
- 装饰者模式(Decorator)的c++实现(改进)
- C++设计模式实现--装饰者模式