Adapt Dont Implement

Context

ModelViewController style application programming in Java, using Swing (the Java GUI standard), or a similar MVC-like GUI toolkit.

Problem

You have some object, nicely modeled to represent your solution domain. Then you have to visualize the object (the model) with more than one widget (view/controller). Each widget has its own set of Events, Listeners, and requires the model to implement a widget-specific model interface.

You can now start to implement one model interface after the other in your class. This creates two problems:

The class gets cluttered with all the model interfaces, the required listener firing, and event creation.

You can not use all the Default/Basic/Abstract... implementations of the model which already exist in Swing. So you start to code esp. all the listener handling from scratch.

Solution

Don't implement all the interfaces at your data model. Instead,

Design the interface of your data model in a generic, domain-specific way.

Provide the data model with a notification/listener interface, allowing the data model to receive notifications specific for the model (see also ObserverObservable).

Use the AdapterPattern (e.g. described in the GangOfFour's book DesignPatterns) to provide widget-specific model interfaces. Adapt the model's get/set methods, as well as its listener/notification methods to the ones needed by the specific widget.

The adapters can be derived from the Default/Basic/Abstract model implementations existing for the widgets under discussion. This gives a head start in listener and event handling. The adapters take an instance of the "real" model as argument in their constructors.

Example

Try to write a class that can be displayed with a JTree, and a JTable (not using the JTreeTable2 stuff currently under discussion).

-- ThomasWeidenfeller


EditText of this page (last edited June 18, 2004) or FindPage with title or text search