装饰者模式
发布时间 : 2024-09-16 04:08
阅读 :
Decorator Pattern 装饰着模式可以在需要扩展某个类的时候,动态地修改而不需要在内部添加代码,也可以防止类爆炸。
装饰者模式可以提供了灵活地扩展方案.
实现 实现一个日志的自定义功能.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 package decoratorimport ( "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()) }
使用 1 2 3 func main () { decorator.Log("Yeah" ,"WWT" ) }
另一种实现形式 不过这次不是日志了.
1 2 3 4 5 6 7 8 9 10 package decoratortype DecoratorFunc func (float64 ) float64 func DecFunc (dec DecoratorFunc) DecoratorFunc{ return func (f float64 ) float64 { result := dec(f) return result } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package mainfunc 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 )) }
注意
装饰者模式是通过注入的方式来装饰被装饰对象的。
装着模式不会修改被装饰对象的接口。
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件