I have a C# class that has some functionality that I’d like to allow a client of the class to override. Specifically I’d like the following:
- If the client does nothing, they get our default behavior
- The client can override the behavior and cause our default behavior to not be called.
- The client can override the behavior and cause our default behavior to be called as a pre/post/middle operation.
My current thinking is to:
- Expose an event that the client would subscribe to if they wanted to override the behavior.
- Expose a method with the default behavior (that matches the signature of the event):
void DefaultBehavior() -
Whenever we attempt to fire the event, if the delegate is null, we call our default behavior method, otherwise, we call the delegate of the event:
if (eventDelegate == null) DefaultBehavior(); else eventDelegate();
When the client overrides the behavior they can optionally call our DefaultBehavior method to get the desired behavior.
Do you think this approach will be intuitive enough from the client’s perspective? Or can you suggest any alternatives that might be better?
Well, if you want your client to override some behavior, why not create a virtual function, an let the client actually
overrideit?It’s the straightforward way of accomplishing this. No need to reinvent the wheel.