设计模式:Go装饰模式
结构型模式
1. 简介
装饰模式向一个现有对象添加新功能或修改原有功能,同时又不改变其原有结构。
优点
- 不修改原有对象添加或修改原有功能。
缺点
- 多层装饰会大幅度提高代码复杂度。
2. UML
3. 演示
3.1. 文件树型图
decorator
├── calc.go
├── calculator.go
├── decorator.go
├── decorator_test.go
└── go.mod
3.2. 代码
calculator.go
package decorator
// 计算器接口
type Calculator interface {
Add(a, b int) int
Minus(a, b int) int
}
calc.go
package decorator
// 计算器实现
type Calc struct {
}
func (c Calc) Add(a, b int) int {
return a + b
}
func (c Calc) Minus(a, b int) int {
return a - b
}
decorator.go
package decorator
import "math"
// 装饰
type CalcDecorator struct {
Calculator
}
func (c CalcDecorator) Minus(a, b int) int {
return int(math.Abs(float64(c.Calculator.Minus(a, b))))
}
func (c CalcDecorator) Multiply(a, b int) int {
return a * b
}
func (c CalcDecorator) Division(a, b int) int {
return a / b
}
decorator_test.go
package decorator
import (
"testing"
)
func TestDecorator(t *testing.T) {
var c Calculator = &Calc{}
calcDecorator := &CalcDecorator{c}
t.Log(calcDecorator.Add(1, 2))
t.Log(calcDecorator.Minus(1, 2))
t.Log(calcDecorator.Multiply(1, 2))
t.Log(calcDecorator.Division(1, 2))
}
3.3. 测试
=== RUN TestDecorator
TestDecorator: decorator_test.go:10: 3
TestDecorator: decorator_test.go:11: 1
TestDecorator: decorator_test.go:12: 2
TestDecorator: decorator_test.go:13: 0
--- PASS: TestDecorator (0.00s)
PASS