mirror of
https://github.com/Estom/notes.git
synced 2026-02-12 23:05:38 +08:00
go知识重新整理
This commit is contained in:
46
Go/DesignPattern/decorator/decorator.go
Normal file
46
Go/DesignPattern/decorator/decorator.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package decorator
|
||||
|
||||
//装饰模式:使用对象组合的方式,动态改变或增加对象行为
|
||||
|
||||
type Component interface {
|
||||
Calc() int
|
||||
}
|
||||
|
||||
type ConcreteComponent struct{}
|
||||
|
||||
func (*ConcreteComponent) Calc() int {
|
||||
return 0
|
||||
}
|
||||
|
||||
//warp mul
|
||||
func WarpMulDecorator(c Component, num int) Component {
|
||||
return &MulDecorator{
|
||||
Component: c,
|
||||
num: num,
|
||||
}
|
||||
}
|
||||
|
||||
type MulDecorator struct {
|
||||
Component
|
||||
num int
|
||||
}
|
||||
|
||||
func (m *MulDecorator) Calc() int {
|
||||
return m.Component.Calc() * m.num
|
||||
}
|
||||
|
||||
func WarpAddDecrator(c Component, num int) Component {
|
||||
return &AddDecrator{
|
||||
Component: c,
|
||||
num: num,
|
||||
}
|
||||
}
|
||||
|
||||
type AddDecrator struct {
|
||||
Component
|
||||
num int
|
||||
}
|
||||
|
||||
func (d *AddDecrator) Calc() int {
|
||||
return d.Component.Calc() + d.num
|
||||
}
|
||||
22
Go/DesignPattern/decorator/decorator_test.go
Normal file
22
Go/DesignPattern/decorator/decorator_test.go
Normal file
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @Author:zhoutao
|
||||
* @Date:2020/12/11 下午3:46
|
||||
* @Desc:
|
||||
*/
|
||||
|
||||
package decorator
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDecrator(t *testing.T) {
|
||||
var c Component = &ConcreteComponent{}
|
||||
c = WarpAddDecrator(c, 10)
|
||||
c = WarpMulDecorator(c, 8)
|
||||
res := c.Calc()
|
||||
if res != 80 {
|
||||
t.Fatalf("expect 80 ,return %d", res)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user