Thursday, May 26, 2011

Dynamic Behavior Addition

Suppose you are building a system that sorts a set of numbers. User has option to choose various algorithms. You allow 3rd party sorting algorithms to be added to system on the fly without needing application restart. All this facilities using a UI. Is it possible to do it? What would be the best way to do it?

My Answer (I have not tried it, but believe it should work.)
1. Create an interface SortAlgorithm containing sort (List) method.
2. Publish its source and .class file.
3. Design a table SortAlgorithms with two columns algo_name and class_name.
4. Provide a UI for 3rd party vendors to upload their concrete implementation for SortAlgorithm.
5. Put the .class file of 4 in class-path and create an entry in the table.
6. Your UI would start listing the new algorithm picked up from the same table.
7. If user chooses new algorithm, load its corresponding class with its name in that table.
8. Your code was always using SortAlgorithm interface so it never needed changes.

Does this approach makes sense to add new behaviors in the system?