Skip to content

Instantly share code, notes, and snippets.

@Jeffwan
Last active February 20, 2022 17:48
Show Gist options
  • Save Jeffwan/7066ee56716d302bf6ce6c6e70ec82eb to your computer and use it in GitHub Desktop.
Save Jeffwan/7066ee56716d302bf6ce6c6e70ec82eb to your computer and use it in GitHub Desktop.
Abstract class and interface in golang
package mxnet
import "fmt"
type ControllerInterface interface {
// Returns the Controller name
Method1() string
// Returns the GroupVersionKind of the API
Method2() string
}
// JobController abstracts other operators to manage the lifecycle of Jobs.
type AbstractJobController struct {
Controller ControllerInterface
}
func (ajc *AbstractJobController) Reconcile() {
// "main logic, need to call controllerInterface"
fmt.Println("result: " + ajc.Controller.Method1() + "," + ajc.Controller.Method2())
}
func (ajc *AbstractJobController) Method1() string {
return "method 1 from abstract controller"
}
// my requirement is in AbstractJobController. it can implements Method1.
/********************************************************************************/
type ConcreteController struct {
AbstractJobController
}
// this is concrete controller path
func NewConcreteController() *ConcreteController{
cc := &ConcreteController{}
jc := AbstractJobController{
Controller: cc,
}
cc.AbstractJobController = jc
return cc
}
// User can choose to override this or not.
func (cc *ConcreteController) Method1() string {
return "method 1 from concreate controller"
}
func (cc *ConcreteController) Method2() string {
return "method 2 from concreate controller"
}
func main() {
c := NewConcreteController()
c.Reconcile()
}
@t-hofmann
Copy link

very helpful! thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment