golang里的struct只能有属性,interface只能有方法定义。这点在java里很好实现的abstractclass在这里就不能直接实现,可以通过struct和interface的结合定义,实现抽象类的类似的功能。 直接上代码: 代码都来之与项目 GitHubgolangfotxxljobexecutor 在这个项目里,重构了executor和默认的RestfulExecutor的实现方式,就是采用了上述的方式。 先定义接口executor执行器typeexecutorinterface{Init初始化执行器Init(opts。。。Option)Run启动服务Run()errorRegistry注册执行器到调度中心Registry()UnRegistry从调度中心在注销执行器UnRegistry()errorSetLogHandler日志handlerSetLogHandler(handlerLogHandler)Stop停止服务Stop()RequestCallback执行后回调请求给调度中心RequestCallback(taskTask,codeint64,msgstring)RegTask注册任务RegTask(patternstring,taskTaskFunc)} 然后定义我们需要的抽象类typeExecutorstruct{executorprivateoptsOptionsaddressstringregListtaskPool注册任务列表runListtaskPool正在执行任务列表loglog4go。LoggerlogHandlerLogHandler日志查询handlerinnerimplexecutor这里很关键,是实现抽象类的重要地方}这里很关键,是实现抽象类的重要地方,封装一个wrap方法,func(eExecutor)wrap(wrapexecutor){e。implwrap} 实现抽象类里的主要方法func(eExecutor)Init(opts。。。Option){for,o:rangeopts{o(e。opts)}e。loge。opts。loggere。regListtaskPool{data:make(map〔string〕Task),}e。runListtaskPool{data:make(map〔string〕Task),}e。addresse。opts。ExecutorIp:e。opts。ExecutorPorte。log。Info(vv,EXECUTOR4GVERSION,e。address)goe。Registry()这里的Regstry是子类需要实现的方法}Registry注册执行器到调度中心func(eExecutor)Registry(){用wrap方式把调用交换具体的子类e。impl。Registry()} 子类实现typeRestFulExecutorstruct{Executormusync。RWMutex}Registry注册执行器到调度中心func(eRestFulExecutor)Registry(){t:time。NewTimer(time。Second0)初始立即执行defert。Stop()。。。。} 最关键的地方,调用funcnewExecutor(opts。。。Option)executor{varexecexecutoroptions:newOptions(opts。。。)ifoptions。executorImplnil{变相的抽象类的实现e:RestFulExecutor{}e。wrap(e)最关键的地方,使用wrap把具体实现子类包装进返回接口e。optsoptionsreturne}else{returnoptions。executorImpl}} 具体代码可以查看项目中的源码 项目地址 GitHubgohutoolboot4goxxljobexecutor:golangfotxxljobexecutor 推荐几个好工具GitHubgohutoolboot4go:abootstrapframeworkforgolanglikeasspringboot GitHubgohutoollog4go:alogkitlikeaslog4jwithgolanguagegolang里的日志工具log4go知乎 golang中的表达式解析expression4go简单的EL知乎