我有3个类似约70%的结构。因此,我想提取一些常见的部分,并使用特定的方法和字段创建一些扩展。
最终结构将如下工作:
.Start()
的方法Common
名为
Start()
从特定部分调用方法.Name()
,后者返回字符串
正在(*Common).Process()
处理返回的结果,有时它应该调用特定的Format()
但是!具体部分必须调用Common part的方法,例如GetVerbosity()
像这样:
package common
type Common struct {
Specificer
}
func (c *Common) Start() {
...
name := Specific.Name()
}
func (c *Common) GetVerbosity() {...}
type Specificer interface {
Name() string
Format() string
}
具体部分:
package specific1
// should implement common.Specificer interface
type Specific1 struct {
// unexported fields
}
func (s *Specific1) Name() string {...}
func (s *Specific1) Format() string {
// How to call it???
Common.Method()
}
这类似于某些框架 - 当另一个代码调用您的代码时,您也称之为代码。
如何更好地实现这一点?以及如何创建新结构? 我试过了:
将Specific
嵌入Common
,嵌入反之亦然:
type Common struct {
Specificer
}
type Specific1 struct {
common.Common
...
}
// But this is little bit insane:
func NewSpecific1() *common.Common {
var s = Specific1{}
return &common.Common{Specificer: &s}
}
定义2个接口:Commoner
和Specificer
。和组合界面:
package common
type CommonSpecificer interface {
Commoner
Specificer
}
type Common struct {...} // implements all the methods from Commoner
func New() *Common {...}
//////
package specific1
type Specific1 struct { // implements all the methods from common.Specificer
Common
...
}
func NewSpecific1() *Specific1 {
c := common.NewCommon(...)
s := &Specific1{Common: c}
return s
}