大话设计模式(golang) 三、装饰模式

模式特点:动态地为对象增加额外的职责
程序实例:展示一个人一件一件穿衣服的过程。

25153151_tVUm.gif

package main

import (
	"fmt"
)

type Finery interface {
	Show()
}

type Person struct {
	Name     string
	Fineries []Finery
}

func (this *Person) Show() {
	fmt.Println("装扮的", this.Name)
	for _, finery := range this.Fineries {
		finery.Show()
	}
}

func (this *Person) Decorate(finery Finery) {
	if this.Fineries == nil {
		this.Fineries = make([]Finery, 0, 0)
	}
	this.Fineries = append(this.Fineries, finery)
}

type TShirts struct {
	Finery
}

func (t *TShirts) Show() {
	fmt.Println("大T恤")
}

type BigTrouser struct {
	Finery
}

func (b *BigTrouser) Show() {
	fmt.Println("大裤衩")
}

type Sneakers struct {
	Finery
}

func (s *Sneakers) Show() {
	fmt.Println("破球鞋")
}

type LeatherShoes struct {
	Finery
}

func (l *LeatherShoes) Show() {
	fmt.Println("皮鞋")
}

type Suit struct {
	Finery
}

func (s *Suit) Show() {
	fmt.Println("西装")
}

type Tie struct {
	Finery
}

func (t *Tie) Show() {
	fmt.Println("领带")
}

func main() {
	person1 := &(Person{"小菜", nil})
	fmt.Println("第一种装扮:")
	dtx := new(TShirts)
	kk := new(BigTrouser)
	pqx := new(Sneakers)
	person1.Decorate(dtx)
	person1.Decorate(kk)
	person1.Decorate(pqx)
	person1.Show()

	person2 := &(Person{"小菜", nil})
	fmt.Println("第二种装扮:")
	px := new(LeatherShoes)
	ld := new(Tie)
	xz := new(Suit)
	person2.Decorate(xz)
	person2.Decorate(ld)
	person2.Decorate(px)
	person2.Show()

	person3 := &(Person{"小菜", nil})
	fmt.Println("第三种装扮:")
	xz2 := new(Suit)
	pqx2 := new(Sneakers)
	kk2 := new(BigTrouser)
	ld2 := new(Tie)
	person3.Decorate(xz2)
	person3.Decorate(ld2)
	person3.Decorate(kk2)
	person3.Decorate(pqx2)
	person3.Show()
}

 

转载于:https://my.oschina.net/zhoukuo/blog/710281

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值