策略模式java 用例_Go 实现常用设计模式(三)策略模式

装饰器模式 (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 协议》,转载必须注明作者和本文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值