go怎么写高质量代码?聊聊go.cqrs的Dispatcher
go怎么写高质量代码?聊聊go.cqrs的Dispatchergo.cqrs的Dispatcher接口定义了Dispatch、RegisterHandler方法;InMemoryDispatcher定义了map[string]CommandHandler属性,其Dispatch方法根据command.CommandType()获取handler,然后执行handler.Handle(command);其RegisterHandler方法遍历commands,然后获取command的type,挨个注册到map[string]CommandHandler中。
序本文主要研究一下go.cqrs的Dispatcher
typeDispatcherinterface{
Dispatch(Commandmessage)error
RegisterHandler(CommandHandler ...interface{})error
}
Dispatcher接口定义了Dispatch、RegisterHandler方法
InMemoryDispatchertypeInMemoryDispatcherstruct{
handlersmap[string]CommandHandler
}
//NewInMemoryDispatcherconstructsanewinmemorydispatcher
funcNewInMemoryDispatcher()*InMemoryDispatcher{
b:=&InMemoryDispatcher{
Handlers:make(map[string]CommandHandler)
}
returnb
}
//DispatchpassestheCommandMessageontoallregisteredcommandhandlers.
func(b*InMemoryDispatcher)Dispatch(commandCommandMessage)error{
ifhandler ok:=b.handlers[command.CommandType()];ok{
returnhandler.Handle(command)
}
returnfmt.Errorf("Thecommandbusdoesnothaveahandlerforcommandsoftype:%s" command.CommandType())
}
//RegisterHandlerregistersacommandhandlerforthecommandtypesspecifiedbythe
//variadicCommandsparameter.
func(b*InMemoryDispatcher)RegisterHandler(handlerCommandHandler commands...interface{})error{
for_ command:=rangecommands{
typeName:=typeOf(command)
if_ ok:=b.handlers[typeName];ok{
returnfmt.Errorf("Duplicatecommandhandlerregistrationwithcommandbusforcommandoftype:%s" typeName)
}
b.handlers[typeName]=handler
}
returnnil
}
InMemoryDispatcher定义了map[string]CommandHandler属性,其Dispatch方法根据command.CommandType()获取handler,然后执行handler.Handle(command);其RegisterHandler方法遍历commands,然后获取command的type,挨个注册到map[string]CommandHandler中
CommandHandler//CommandHandleristheinterfacethatallcommandhandlersshouldimplement.
typeCommandHandlerinterface{
Handle(CommandMessage)error
}
//CommandMessageistheinterfacethatacommandmessagemustimplement.
typeCommandMessageinterface{
//AggregateIDreturnstheIDoftheAggregatethatthecommandrelatesto
AggregateID()string
//Headersreturnsthekeyvaluecollectionofheadersforthecommand.
Headers()map[string]interface{}
//SetHeadersetsthevalueoftheheaderspecifiedbythekey
SetHeader(string interface{})
//Commandreturnstheactualcommandwhichisthepayloadofthecommandmessage.
Command()interface{}
//CommandTypereturnsastringdescriptorofthecommandname
CommandType()string
}
CommandHandler接口定义了Handle方法;CommandMessage接口定义了AggregateID、Headers、SetHeader、Command、CommandType方法
小结go.cqrs的Dispatcher接口定义了Dispatch、RegisterHandler方法;InMemoryDispatcher定义了map[string]CommandHandler属性,其Dispatch方法根据command.CommandType()获取handler,然后执行handler.Handle(command);其RegisterHandler方法遍历commands,然后获取command的type,挨个注册到map[string]CommandHandler中。
doc- go.cqrs