【寒江雪】Go实现装饰者模式

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))
}

注意

  • 装饰者模式是通过注入的方式来装饰被装饰对象的。
  • 装着模式不会修改被装饰对象的接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值