设计模式 decorator 实现

2022-07-21 浏览 (1222)

golang 设计模式 decorator 代码实现

package decorator

type Component interface {
	Calc() int
}

type ConcreteComponent struct{}

func (*ConcreteComponent) Calc() int {
	return 0
}

type MulDecorator struct {
	Component
	num int
}

func WarpMulDecorator(c Component, num int) Component {
	return &MulDecorator{
		Component: c,
		num:       num,
	}
}

func (d *MulDecorator) Calc() int {
	return d.Component.Calc() * d.num
}

type AddDecorator struct {
	Component
	num int
}

func WarpAddDecorator(c Component, num int) Component {
	return &AddDecorator{
		Component: c,
		num:       num,
	}
}

func (d *AddDecorator) Calc() int {
	return d.Component.Calc() + d.num
}

目录

go 设计模式

相关文章

装饰模式

设计模式 decorator_test 实现

  • 所属分类: 后端技术
  • 本文标签: golang
  • 版权声明: 本文链接 https://seaxiang.com/blog/7005873b2b1e42cd9137f464278fb6bc