小编use*_*186的帖子

在Golang中实现模板方法模式的优雅方式

在Go中实现模板方法模式是否有一种优雅的规范方法?在C++中,它看起来像这样:

#include <iostream>
#include <memory>

class Runner {
public:
    void Start() {
        // some prepare stuff...
        Run();
    }
private:
    virtual void Run() = 0;
};

class Logger : public Runner {
private:
    virtual void Run() override {
        std::cout << "Running..." << std::endl;
    }
};

int main() {
    std::unique_ptr<Runner> l = std::make_unique<Logger>();
    l->Start();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在golang我写了这样的东西:

package main

import (
    "fmt"
    "time"
)

type Runner struct {
    doRun func()
    needStop bool
}

func (r *Runner) Start() {
    go r.doRun()
} …
Run Code Online (Sandbox Code Playgroud)

c++ go template-method-pattern

5
推荐指数
2
解决办法
1590
查看次数

标签 统计

c++ ×1

go ×1

template-method-pattern ×1