mercredi 18 août 2021

Golang extension interface pattern in multiple packages

I am trying to apply the extension interface pattern in Go, but I am running into an issue of cyclical imports.

I have a base class A, where I would like to 'override' some of the methods, while still maintaining access to the old ones as well. For this reason I have introduced a new class B, which is helping me to choose the right instance (C or D in this example). As C or D can be quite complicated, I would like to keep them in separate packages for ease of testing. In this current setup, I will run into an issue of cyclical imports, because package A is referring to package C, which is pointing again to A. How could I solve this problem? Thanks!

package A


type A interface {
   Create(input string) error
   Delete(input string) error
}


type B interface {
    A
}


func newTypeB(base A) B {
  switch base.type {
    case "C":
        return c.New(base)
    case "D":
        return d.New(base)
    default:
        return base
  }
}


///////////////////
package c


type C interface {
    B
}


func New(base A) C {
    return C{A}
}

func (c *C) Create(input string) error {
    c.B.Create(input)
    // do other stuff
    return nil
}

// similar implementation for D in a separate package
......

Aucun commentaire:

Enregistrer un commentaire