Created
November 29, 2022 11:21
-
-
Save jbw/6dd4f6f9e67fec80ae00fe4203e8314e to your computer and use it in GitHub Desktop.
Basic 1 to 1 command handler separation example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package command_handler_pattern | |
import ( | |
"reflect" | |
) | |
type NotificationHandler[TNotification any] interface { | |
Handle(notification TNotification) error | |
} | |
var notificationHandlers map[string]interface{} = make(map[string]interface{}) | |
func RegisterNotificationHandler[TNotification any](notification TNotification, handler NotificationHandler[TNotification]) { | |
notificationHandlers[typeOf(notification).Name()] = handler | |
} | |
func Send[T any](request T) { | |
t := reflect.TypeOf(request).Name() | |
handler := notificationHandlers[t] | |
handlerValue := handler.(NotificationHandler[T]) | |
handlerValue.Handle(request) | |
} | |
func typeOf(v interface{}) reflect.Type { | |
return reflect.TypeOf(v) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment