Skip to content

Commit

Permalink
add decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
senghoo committed Apr 8, 2016
1 parent ad60e3c commit 1bf2afb
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
7 changes: 7 additions & 0 deletions 20_decorator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# 装饰模式

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

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

使用匿名组合,在装饰器中不必显式定义转调原对象方法。
43 changes: 43 additions & 0 deletions 20_decorator/decorator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
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
}
14 changes: 14 additions & 0 deletions 20_decorator/decorator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package decorator

import "fmt"

func ExampleDecorator() {
var c Component = &ConcreteComponent{}
c = WarpAddDecorator(c, 10)
c = WarpMulDecorator(c, 8)
res := c.Calc()

fmt.Printf("res %d\n", res)
// Output:
// res 80
}

0 comments on commit 1bf2afb

Please sign in to comment.