You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nnet/lifetime/lifetime.go

53 lines
810 B
Go

package lifetime
import "git.noahlan.cn/noahlan/nnet/entity"
type (
Handler func(entity entity.NetworkEntity)
Lifetime interface {
OnClosed(h Handler)
OnOpen(h Handler)
}
Mgr struct {
onOpen []Handler
onClosed []Handler
}
)
func NewLifetime() *Mgr {
return &Mgr{
onOpen: make([]Handler, 0),
onClosed: make([]Handler, 0),
}
}
func (lt *Mgr) OnClosed(h Handler) {
lt.onClosed = append(lt.onClosed, h)
}
func (lt *Mgr) OnOpen(h Handler) {
lt.onOpen = append(lt.onOpen, h)
}
func (lt *Mgr) Open(entity entity.NetworkEntity) {
if len(lt.onOpen) <= 0 {
return
}
for _, handler := range lt.onOpen {
handler(entity)
}
}
func (lt *Mgr) Close(entity entity.NetworkEntity) {
if len(lt.onClosed) <= 0 {
return
}
for _, handler := range lt.onClosed {
handler(entity)
}
}