Golang设计模式之装饰器模式

Jackey Golang 2,676 次浏览 , , 没有评论

创建文件Component.go

package Deacorator

type Component interface {
    Calc() int
}

type ConcreateComponent struct {
}

func (*ConcreateComponent) Calc() int {
    return 0
}

创建文件AddComponent.go

package Deacorator

type AddComponent struct {
    Component
    num int
}

func WarpAddComponent(component Component, num int) Component {
    return &AddComponent{component, num}
}

// 加法
func (add *AddComponent) Calc() int {
    return add.Component.Calc() + add.num
}

创建文件MulComponent.go

package Deacorator

type MulComponent struct {
    Component
    num int
}

func WarpMulComponent(component Component, num int) Component {
    return &MulComponent{component, num}
}

// 乘法
func (mul *MulComponent) Calc() int {
    return mul.Component.Calc() * mul.num
}

main.go

package main

import (
    "fmt"
    "test/design/Deacorator"
)

func main() {
    var c Deacorator.Component = &Deacorator.ConcreateComponent{}
    //c = Deacorator.WarpAddComponent(c, 10)
    c = Deacorator.WarpMulComponent(c, 10)
    fmt.Println(c.Calc())
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go