Golang – 常用设计Decoration Pattern

在 Golang当中,Decoration Pattern通常用于动态地给一个基础Object添加一些额外的职责,而不需要修改基础Object的代码。这种模式通过创建一个包装(Wrapper)对象来实现,在这个包装Object中可以添加新的功能或修改原始Object的行为。

代码演示:

    1. 定义好Coffee interface的标准接口
    type Coffee interface {
    	Cost() int
    	Ingredients() string
    }

    2. 定义好,符合Coffee的物种,也就是Starbuck Coffee

    type StarBuckCoffee struct{}
    
    func (this *StarBuckCoffee) Cost() int {
    	return 10
    }
    func (this *StarBuckCoffee) Ingredients() string {
    	return "Coffee"
    }

    3.定义好,Coffee的添加物,只能接受Coffe的导入

    type Milk struct {
    	Coffee
    }
    
    func (this *Milk) Cost() int {
    	return this.Coffee.Cost() + 2
    }
    func (this *Milk) Ingredients() string {
    	return this.Coffee.Ingredients() + " Milk"
    }

    4. 使用案例

    func main() {
    	coffee := StarBuckCoffee{}
    	fmt.Println("Cost:", coffee.Cost(), "Ingredients:", coffee.Ingredients())
    
    	coffeeWithMilk := Milk{Coffee: &coffee}
    	fmt.Println("Cost:", coffeeWithMilk.Cost(), "Ingredients:", coffeeWithMilk.Ingredients())
    }

    输出结果:

    Cost: 10 Ingredients: Coffee
    Cost: 12 Ingredients: Coffee Milk

    Loading

    Facebook评论