创建文件Component.go
package Deacorator type Component interface { Calc() int } type ConcreateComponent struct { } func (*ConcreateComponent) Calc() int { return 0 }
创建文件AddComponent.go
package Deacorator type AddComponent struct { Component num int } func WarpAddComponent(component Component, num int) Component { return &AddComponent{component, num} } // 加法 func (add *AddComponent) Calc() int { return add.Component.Calc() + add.num }
创建文件MulComponent.go
package Deacorator type MulComponent struct { Component num int } func WarpMulComponent(component Component, num int) Component { return &MulComponent{component, num} } // 乘法 func (mul *MulComponent) Calc() int { return mul.Component.Calc() * mul.num }
main.go
package main import ( "fmt" "test/design/Deacorator" ) func main() { var c Deacorator.Component = &Deacorator.ConcreateComponent{} //c = Deacorator.WarpAddComponent(c, 10) c = Deacorator.WarpMulComponent(c, 10) fmt.Println(c.Calc()) }