如何在 Go 中实现抽象类? [英] How to implement an abstract class in Go?

查看:56
本文介绍了如何在 Go 中实现抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Go 中实现抽象类?由于 Go 不允许我们在接口中有字段,这将是一个无状态对象.那么,换句话说,Go 中的方法是否可以有某种默认实现?

How to implement an abstract class in Go? As Go doesn't allow us to have fields in interfaces, that would be a stateless object. So, in other words, is it possible to have some kind of default implementation for a method in Go?

举个例子:

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

func (daemon *Daemon) start(duration time.Duration) {
    ticker := time.NewTicker(duration)

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

type ConcreteDaemonA struct { foo int }
type ConcreteDaemonB struct { bar int }

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

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

func main() {
    dA := new(ConcreteDaemonA)
    dB := new(ConcreteDaemonB)

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

    time.Sleep(100 * time.Second)
}

这不会编译,因为不可能将接口用作接收器.

This won't compile as it's not possible to use interface as a receiver.

事实上,我已经回答了我的问题(见下面的答案).但是,这是实现这种逻辑的惯用方法吗?除了语言的简单性之外,还有什么理由不用默认实现吗?

In fact, I have already answered my question (see the answer below). However, is it an idiomatic way to implement such logic? Are there any reasons not to have a default implementation besides language's simplicity?

推荐答案

一个简单的解决方案是将 daemon *Daemon 移动到参数列表中(从而删除 start(...) 来自界面):

An easy solution is to move daemon *Daemon to the argument list (thus removing start(...) from the interface):

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

func start(daemon Daemon, duration time.Duration) { ... }

func main() {
    ...
    start(dA, 1 * time.Second)
    start(dB, 5 * time.Second)
    ...
}

这篇关于如何在 Go 中实现抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆