forked from senghoo/golang-design-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# 装饰模式 | ||
|
||
装饰模式使用对象组合的方式动态改变或增加对象行为。 | ||
|
||
Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。 | ||
|
||
使用匿名组合,在装饰器中不必显式定义转调原对象方法。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |