lundi 13 avril 2020

How to implement an interface with functions sharing the same logic?

I'd like to provide multiple implementations for the following interface:

type API interface {
    A()
    B()
    C()
}

According to my use cases, all implementations should share the exact same logic for function A and B while function C will have different logic for different implementations.

So I've created the following common implementation to be embedded:

type Common struct {}

func (c *Common) A() {}
func (c *Common) B() {}

To create two implementations for the interface above, I can just do the following:

type FirstImpl struct { Common }

func (i *FirstImpl) C() {}

type SecondImpl struct { Common }

func (i *SecondImpl) C() {}

Everything works just fine until I find out that function C needs to be called inside function B. Note that the logic for function B should still be the same across two implementations despite that we may get different results calling C inside B.

I'm wondering if this is a common pattern in Go and if there is an elegant way to handle it.

Aucun commentaire:

Enregistrer un commentaire