嵌入相互依赖的结构/接口

时间:2018-04-24 11:43:46

标签: go interface structure embedding

我有3个类似约70%的结构。因此,我想提取一些常见的部分,并使用特定的方法和字段创建一些扩展。

最终结构将如下工作:

    来自.Start()
  1. 方法Common名为

  2. Start()从特定部分调用方法.Name(),后者返回字符串

  3. 正在(*Common).Process()处理返回的结果,有时它应该调用特定的Format()

  4. 但是!具体部分必须调用Common part的方法,例如GetVerbosity()

  5. 像这样:

    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() 
    }
    

    这类似于某些框架 - 当另一个代码调用您的代码时,您也称之为代码。

    如何更好地实现这一点?以及如何创建新结构? 我试过了:

    1. 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. 定义2个接口:CommonerSpecificer。和组合界面:

      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
      }
      

0 个答案:

没有答案