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;
}
golangで私は次のようなものを書きました:
package main
import (
"fmt"
"time"
)
type Runner struct {
doRun func()
needStop bool
}
func (r *Runner) Start() {
go r.doRun()
}
func NewRunner(f func()) *Runner {
return &Runner{f, false}
}
type Logger struct {
*Runner
i int
}
func NewLogger() *Logger {
l := &Logger{}
l.doRun = l.doRunImpl
return l
}
func (l *Logger) doRunImpl() {
time.Sleep(1 * time.Second)
fmt.Println("Running")
}
func main() {
l := NewLogger()
l.Start()
fmt.Println("Hello, playground")
}
しかし、このコードは実行時のヌル ポインター エラーで失敗します。基本的な考え方は、派生クラス (go 構造体) から基本クラス ルーチンにいくつかの機能を組み合わせて、この mix-in 派生ルーチンから基本クラスの状態を利用できるようにすることです。