您的位置:首页 > 编程语言 > Go语言

【寒江雪】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))
}


注意

装饰者模式是通过注入的方式来装饰被装饰对象的。

装着模式不会修改被装饰对象的接口。

有钱的捧个钱场,没钱的捧个人场。

出来混不容易。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: