DEV Community

Discussion on: Idiomatic way to implement this in golang

Collapse
 
kashyaprahul94 profile image
Rahul Kashyap • Edited

A quick thought says Inheritance is not really a game in Go, however it embraces EmbeddedTypes for something similar.

Roughly -

type BaseSensor struct {
}

func (bs *BaseSensor) BeforeStart() {
    fmt.Println("Base Before Start")
}

func (bs *BaseSensor) AfterStart() {
    fmt.Println("Base After Start")
}

func (bs *BaseSensor) ShutdownStart() {
    fmt.Println("Base Shutdown")
}

func (bs *BaseSensor) Process() {
    fmt.Println("Base Process. You can panic here if you want it to be really abstract")
}

type SensorA struct {
    *BaseSensor
}

func (sa *SensorA) Process() {
    fmt.Println("Sensor A Process")
}

type SensorB struct {
    *BaseSensor
}

func (sb *SensorB) BeforeStart() {
    // If you want to call super like method
    sb.BaseSensor.BeforeStart()

    fmt.Println("Sensor B BeforeStart")
}

func (sb *SensorB) Process() {

    fmt.Println("Sensor B Process")
}

And then you can invoke them as follows -

    sensorA := &SensorA{
        BaseSensor: &BaseSensor{},
    }

    sensorA.Process()

    sensorB := &SensorB{
        BaseSensor: &BaseSensor{},
    }

    sensorB.BeforeStart()
    sensorB.Process()

Collapse
 
julianchu profile image
Julian-Chu

Rahul already made the important part, I'd like to add code for Work()


type ISensor interface {
    BeforeStart()
    AfterStart()
    ShutdownStart()
    Process()
}

type SensorWorker struct {
    sensor ISensor
}


func (w SensorWorker) Work() {
    w.sensor.BeforeStart()
    w.sensor.AfterStart()
    w.sensor.Process()
    w.sensor.ShutdownStart()
}

then you can do something like following:


func main() {
    sensorWorker:= &SensorWorker{sensor:sensorA}
    sensorWorker.Work()
    sensorWorker.sensor = sensorB
    sensorWorker.Work()
}

Collapse
 
ahmednawazkhan profile image
Ahmed Nawaz Khan

thanks