I’m brainstorming some ideas around a pattern to use for the following scenario.
I have some 3rd party controls that I want to add common functionality to. Functionality is added by handling several of the the events and doing certain things when the events fire along with adding some private variables to hold some state info between events. I want to reuse the code and functionality so this is what I’d typically do.
Create a class for this functionality and pass in the instance of the control that I want to add the functionality to in the constructor.
Then I can add event handlers to the control in the instance of the class.
Can anyone think of alternative patterns to use in order to create this kind of reusable functionality?
The most applicable “Design Pattern” is Observer. The reusable functionality you want to develop can be implemented as simple observers of Control, which subscribe to some subset of Control events. Fortunately, Windows Forms Controls implement many events, making it possible to add functionality from outside the class almost as easily as from within, by the usual sub-classing.
For example, you could add drag and drop support by implementing an observer that subscribed to DragOver and DragDrop (and possibly DragLeave) and performed the appropriate actions based on the DragDropEvent data.
This is an excellent technique to consider, as it allows you to develop such functionality once and add it to many Controls.