我正在阅读一本设计模式书,并试图将这些模式应用到Go中,以此来学习两者。
目前,我已经达到了decorator模式,我遇到了一个我很好奇的场景。
以下是一些示例代码:
type Beverage interface {
getDescription() string
cost() float64
}
type HouseBlend struct{}
func (hb *HouseBlend) getDescription() string {
return "House Blend Coffee"
}
func (hb *HouseBlend) cost() float64 {
return .89
}
type Mocha struct {
b Beverage
}
func (m *Mocha) getDescription() string {
return m.b.getDescription() + ", Mocha"
}
func (m *Mocha) cost() float64 {
return m.b.cost() + .20
}
之间有什么区别
var hb Beverage = &HouseBlend{}
//This works since hb is an interface type
hb = &Mocha{
b: hb,
}
和
hb := &HouseBlend{}
//This assignment fails since Mocha is not type HouseBlend
hb = &Mocha{
b: hb,
}
这也适用于
hb := *new(Beverage)
hb = &Espresso{}
hb = &Mocha{
b: hb,
}
有没有一种简写的方法可以给我的变量hb接口类型,或者它是否需要显式才能";装饰";我的结构,并将变量重新分配给不同的类型?
任何关于改进这里的decorator模式和实现干净多态性的建议都是受欢迎的。非常感谢。
var hb Beverage
是显式赋予变量类型的方式。隐式键入总是得到你输入的值的类型;简写";这里,由于var name Type
已经很短了,但如果你真的想使用一个短的变量声明,你可以使用一个类型转换:
hb := Beverage(&HouseBlend{})
您可以使用缩写形式,并使用将hb
声明为接口
hb:=Beverage(&HouseBlend{})
这段代码并不完全正确:
// You allocate a pointer to an interface, and redirect it to get an uninitialized interface value
hb := *new(Beverage)
// Here, you throw away the value of the first assignment
hb = &Espresso{}