Open AmitKumarDas opened 5 years ago
:bulb: Let us extend above scenario further
type FilteringResourceEventHandler struct {
FilterFunc func(obj interface{}) bool
// uses interface & not struct ... which is good
// let the struct be utilised by callers
// remember the go proverb `accept interface & return struct`
Handler ResourceEventHandler
}
// OnAdd calls the nested handler only if the filter succeeds
func (r FilteringResourceEventHandler) OnAdd(obj interface{}) {
if !r.FilterFunc(obj) {
return
}
r.Handler.OnAdd(obj)
}
// OnUpdate ensures the proper handler is called depending on
// whether the filter matches
func (r FilteringResourceEventHandler) OnUpdate(oldObj, newObj interface{}) {
newer := r.FilterFunc(newObj)
older := r.FilterFunc(oldObj)
switch {
case newer && older:
r.Handler.OnUpdate(oldObj, newObj)
case newer && !older:
r.Handler.OnAdd(newObj)
case !newer && older:
r.Handler.OnDelete(oldObj)
default:
// do nothing
}
}
// OnDelete calls the nested handler only if the filter succeeds
func (r FilteringResourceEventHandler) OnDelete(obj interface{}) {
if !r.FilterFunc(obj) {
return
}
r.Handler.OnDelete(obj)
}
refer - k8s.io/client-go
:nerd_face: Your function can be an implementation of an interface
:worried: What if there are multiple contracts exposed from the interface :bulb: Define a function per contract & compose all of them within a struct
:nerd_face: specify as many or as few via below struct
:bulb: Above solution also solves the problem of an interface that exposes multiple contracts. In other words, a struct that embeds above struct need not implement all the contracts since the embedded struct has implemented all the contracts.