开发者

Design pattern to encapsulate common functionality among UI controls

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?


You may want to take a look at the:

  1. Facade Pattern
  2. Decorator pattern
  3. Observer pattern

The facade pattern will allow for you to encapsulate the behavior of the control under the current class. The decorator pattern will allow for you to be able to create stackable controls. The observer pattern will allow for you to manage events.


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.


I feel that the Observer pattern should be helpful. This is how you can use it :

UtilityClass which accepts a control (as you have mentioned): make it observer

Register various Utility classes (and hence controls) to various Events it is interested in : Observable

Now when a particular event occurs it updates various observers where you can delegate the basic eventHandling to the control it is wrapping and also have a place to do custom handling based on the control and event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜