Home >Backend Development >Golang >How Can Abstract Classes Be Implemented in Go?

How Can Abstract Classes Be Implemented in Go?

DDD
DDDOriginal
2024-11-29 10:50:11490browse

How Can Abstract Classes Be Implemented in Go?

Implementing Abstract Classes in Go

In Go, abstract classes are not natively supported. However, it is possible to emulate abstract class behavior by using an approach that involves:

  1. Defining an interface with the desired abstract methods.
  2. Creating a type with embedded receiver that fulfills the interface and provides default implementations for the methods.

Example

Consider the following code, which defines an abstract type Daemon with the methods start and doWork:

type Daemon interface {
    start(time.Duration)
    doWork()
}

To provide default implementations, we can create an abstract type (e.g., AbstractDaemon) that embeds the Daemon interface and provides default implementations for the methods:

type AbstractDaemon struct {
    Daemon
}

func (a *AbstractDaemon) start(duration time.Duration) {
    ticker := time.NewTicker(duration)

    // this will call daemon.doWork() periodically
    go func() {
        for {
            <-ticker.C
            a.doWork()
        }
    }()
}

Concrete Types

Now, we can create concrete types that inherit from the AbstractDaemon type and provide implementations for the doWork method:

type ConcreteDaemonA struct {
    *AbstractDaemon
    foo int
}

func (a *ConcreteDaemonA) doWork() {
    a.foo++
    fmt.Println("A: ", a.foo)
}

type ConcreteDaemonB struct {
    *AbstractDaemon
    bar int
}

func (b *ConcreteDaemonB) doWork() {
    b.bar--
    fmt.Println("B: ", b.bar)
}

Usage

We can use these concrete types to create instances and invoke their methods:

var dA Daemon = newConcreteDaemonA()
var dB Daemon = newConcreteDaemonB()

dA.start(1 * time.Second)
dB.start(5 * time.Second)

time.Sleep(100 * time.Second)

This approach provides a mechanism for implementing abstract classes in Go, allowing for default method implementations and multiple inheritance through embedding.

The above is the detailed content of How Can Abstract Classes Be Implemented in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn