Understand how adapters let disparate systems work togethe
Pretend you're back in 1999 and you've just landed a job with a dot-com. Much of your compensation comes from stock options, and you are content. Fortunately, your work is interesting. You're developing an application builder that lets users visually construct Swing applications. So you seize upon a novel idea: display a view's component hierarchy next to the view itself like this:
A user interface (UI) builder prototype. Click on thumbnail to view full-size image.
The left panel shows the component hierarchy for the upper-right panel, and the lower-right panel contains a button that updates the tree. The idea, of course, is that users drag components into the upper-right panel and subsequently click the show component tree button to update the tree. In this simple prototype, you're only interested in getting the tree to reflect the upper-right panel's component hierarchy; you'll leave the drag and drop to someone else.
You propose this idea of exposing component trees to your colleagues, and they are enthusiastic. How long, they wonder, will it take to implement? The response is up to you, but as we're about to find out, the Adapter design pattern makes this an easy job.
Introducing Adapter
Adapters are necessary because dissimilar elements need to interoperate. From wrenches to computer networks, physical adapters are abundant. In software, adapters make dissimilar software packages work together; for example, you might have a tree of objects (call them Nodes) you want to display using Swing's JTree. The JTree class can't display your Nodes directly, but it can display TreeNode instances. With an adapter, you can map your Nodes to TreeNodes. Because Swing trees use the Adapter pattern, you can display any kind of tree—from Document Object Model (DOM) to Swing component hierarchies to a compiler parse tree—just by implementing a simple adapter.
In Design Patterns, the authors describe the Adapter pattern like this:
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
No comments:
Post a Comment