装饰器模式 (decorator)
意图:
装饰器模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
关键代码:
装饰器和被装饰对象实现同一个接口,装饰器中使用了被装饰对象
应用实例:
JAVA中的IO流
new DataInputStream(new FileInputStream("test.txt"));
Go实现装饰器模式
package decorator
import "fmt"
type Person interface {
cost() int
show()
}
// 被装饰对象
type laowang struct {
}
func (*laowang) show() {
fmt.Println("赤裸裸的老王。。。")
}
func (*laowang) cost() int {
return 0
}
// 衣服装饰器
type clothesDecorator struct {
// 持有一个被装饰对象
person Person
}
func (*clothesDecorator) cost() int {
return 0
}
func (*clothesDecorator) show() {
}
// 夹克
type Jacket struct {
clothesDecorator
}
func (j *Jacket) cost() int {
return j.person.cost() + 10
}
func (j *Jacket) show() {
// 执行已有的方法
j.person.show()
fmt.Println("穿上夹克的老王。。。")
}
// 帽子
type Hat struct {
clothesDecorator
}
func (h *Hat) cost() int {
return h.person.cost() + 5
}
func (h *Hat) show() {
fmt.Println("戴上帽子的老王。。。")
}
测试用例
package decorator
import (
"fmt"
"testing"
)
func TestDecorator(t *testing.T) {
laowang := &laowang{}
jacket := &Jacket{}
jacket.person = laowang
jacket.show()
hat := &Hat{}
hat.person = jacket
hat.show()
fmt.Println("cost:", hat.cost())
}
具体代码
更详细的代码可参考:https://github.com/pibigstar/go-demo 里面包含了 Go 常用的设计模式、Go 面试易错点、简单的小项目(区块链,爬虫等)、还有各种第三方的对接(redis、sms、nsq、elsticsearch、alipay、oss...),如果对你有所帮助,请给个 Star,你的支持,是我最大的动力!
本作品采用《CC 协议》,转载必须注明作者和本文链接