婺源网站建制作,跨境电商平台有哪些推广方式,网络推广平台,在哪制作一个简单的网页装饰模式使用对象组合的方式动态改变或增加对象行为。
Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。
使用匿名组合#xff0c;在装饰器中不必显式定义转调原对象方法。
decorator.go
package decoratortype Component interface {Calc() int
}type Concre…装饰模式使用对象组合的方式动态改变或增加对象行为。
Go语言借助于匿名组合和非入侵式接口可以很方便实现装饰模式。
使用匿名组合在装饰器中不必显式定义转调原对象方法。
decorator.go
package decoratortype Component interface {Calc() int
}type ConcreteComponent struct{}func (*ConcreteComponent) Calc() int {return 0
}type MulDecorator struct {Componentnum int
}func WarpMulDecorator(c Component, num int) Component {return MulDecorator{Component: c,num: num,}
}func (d *MulDecorator) Calc() int {return d.Component.Calc() * d.num
}type AddDecorator struct {Componentnum int
}func WarpAddDecorator(c Component, num int) Component {return AddDecorator{Component: c,num: num,}
}func (d *AddDecorator) Calc() int {return d.Component.Calc() d.num
}decorator_test.go
package decoratorimport fmtfunc ExampleDecorator() {var c Component ConcreteComponent{}c WarpAddDecorator(c, 10)c WarpMulDecorator(c, 8)res : c.Calc()fmt.Printf(res %d\n, res)// Output:// res 80
}