Go 设计模式--装饰模式

装饰模式使用对象组合的方式动态改变或增加对象行为。

Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。

使用匿名组合,在装饰器中不必显式定义转调原对象方法。

package decorator

import (
	_ "fmt"
)

type BaseCal interface{
	Cal() int
}

//电脑实例
type Computer struct{
//啥功能也没有
}

func (this *Computer)Cal()int{
	return 0
}

func NewComputer() BaseCal{
	return &Computer{}
}

type AddDecorator struct{
	BaseCal
	num int
}

func (this *AddDecorator)Cal()int{
	return this.BaseCal.Cal() + this.num
}

//给Computer添加一个add功能
func NewAdd(comp BaseCal,num int) BaseCal{
	return &AddDecorator{
		BaseCal : comp,
		num : num,
	}
}

type MulDecorator struct{
	BaseCal
	num int
}

//给Computer添加一个*功能
func (this *MulDecorator)Cal()int{
	return this.BaseCal.Cal() * this.num
}

func NewMul(comp BaseCal,num int) BaseCal{
	return &MulDecorator{
		BaseCal : comp,
		num : num,
	}
}

  

	c := decorator.NewComputer()
	c = decorator.NewAdd(c,10)
	c = decorator.NewMul(c,9)
	fmt.Println(c.Cal())//输出:90

  

猜你喜欢

转载自www.cnblogs.com/flycc/p/12632130.html
今日推荐