Last active
February 20, 2022 17:48
-
-
Save Jeffwan/7066ee56716d302bf6ce6c6e70ec82eb to your computer and use it in GitHub Desktop.
Abstract class and interface in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very helpful! thanks