Summary
The Adapter pattern lets you use an existing class to meet a client class’s needs. When a client specifies its requirements in an interface, you can usually create a new class that implements the interface and subclasses an existing class. This approach creates a class adapter that translates a client’s calls into calls to the existing class’s methods.
When a client does not specify the interface it requires, you may still be able to apply Adapter, creating a new client subclass that uses an instance of the existing class. This approach creates an object adapter that forwards a client’s calls to an instance of the existing class. This approach can be dangerous, especially if you don’t (or perhaps can’t) override all the methods that the client might call.
The JTable component in Swing is a good example of a class whose developers applied the Adapter pattern. A JTable component sets itself up as a client that needs table information as defined by the TableModel interface. This makes it easy for you to write an adapter that feeds the table data from domain objects, such as instances of the Rocket class.
To use JTable, you frequently write an object adapter that delegates calls to instances of an existing class. Two aspects of JTable make it less likely that you’ll use a class adapter. First, you will usually create your table adapter as a subclass of AbstractTableModel, so you can’t also subclass your existing class. Second, the JTable class requires a collection of objects, and an object adapter is best suited to adapt information from more than one object.
When you design your own systems, consider the power and flexibility that you and other developers can derive from an architecture that uses Adapter to advantage.