Skip to content

Commit

Permalink
装饰器模式
Browse files Browse the repository at this point in the history
  • Loading branch information
zhongyu mao committed Nov 30, 2023
1 parent 98e4b0e commit efb2d18
Show file tree
Hide file tree
Showing 9 changed files with 95 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
尽可能的详细的展示每一种设计模式的实现及实际使用场景


- [单例模式](01singleton/README.md)
- [单例模式](singleton/README.md)
- [装饰器模式](decorator/README.md)



Expand Down
7 changes: 7 additions & 0 deletions decorator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
## 装饰器模式


装饰器模式是指不在改变现有对象结构的情况下,动态地给改对象增加一些功能的设计模式


实例增加 装饰的组建(如手机基础组件) . 在实例进行执行功能的时候,自动加装饰的部分代码进行执行
57 changes: 57 additions & 0 deletions decorator/decorator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/**
User: cr-mao
Date: 2023/11/30 22:05
Email: crmao@qq.com
Desc: decorator.go
*/
package decorator

type Phone interface {
GetPrice() float32
}

//装饰
type Decorator struct {
Phone Phone
}

//装饰设置组件方法
func (d *Decorator) SetComponent(c Phone) {
d.Phone = c
}

//装饰方法
func (d *Decorator) GetPrice() {
if d.Phone != nil {
d.Phone.GetPrice()
}
}

//基础零件
type BaseParts struct {
}

//获取基础零件手机价格
func (p *BaseParts) GetPrice() float32 {
return 2000
}

type IPhone struct {
Decorator
}

//获取IPhone价格
func (c *IPhone) GetPrice() float32 {
phonePrice := c.Phone.GetPrice()
return phonePrice + 6000
}

type Xiaomi struct {
Decorator
}

//小米手机的价格
func (c *Xiaomi) GetPrice() float32 {
phonePrice := c.Phone.GetPrice()
return phonePrice + 1000
}
29 changes: 29 additions & 0 deletions decorator/decorator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
User: cr-mao
Date: 2023/11/30 22:20
Email: crmao@qq.com
Desc: decorator_test.go
*/
package decorator

import (
"fmt"
"testing"
)

func TestDecorator(t *testing.T) {
//具体零件
phone := &BaseParts{}
fmt.Printf("基础零件的价格为:%f\n", phone.GetPrice())

//定义添加IPhone手机
iPhone := &IPhone{}
iPhone.SetComponent(phone)
fmt.Printf("苹果的价格为:%f\n", iPhone.GetPrice())

//定义添加Xiaomi手机
xiaomi := &Xiaomi{}
xiaomi.SetComponent(phone)
fmt.Printf("小米的价格为:%f\n", xiaomi.GetPrice())

}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit efb2d18

Please sign in to comment.