Applied Design Patterns with Java

Structural :: Adapter (137) {C ch 9}

Intent
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that otherwise couldn't because of incompatible interfaces.

As Known As
Wrapper


Motivation

Sometimes a toolkit class designed for reuse isn't reusable only because its interface doesn't match the domain-specific interface an application requires.

Consider a drawing editor that lets users draw and arrange graphical elements into pictures and diagrams. The drawing editor's key abstraction is the graphical object, which has an editable shape and can draw itself. The interface for graphical objects is defined by an abstract class called Shape. The editor defines a subclass of Shape for each kind of graphical object: a LineShape class for lines, a PolygonShape class for polygons, etc.

But a TextShape subclass that can display and edit text is considerably more difficult to implement, since even basic text editing involves complicated screen update and buffer management. So can't use TextView and Shape objects can't be used interchangeably.

Define TextShape so that it adapts the TextView interface to Shape's,in one of two ways: (1) by inheriting Shape's interface and TextView's implementation or (2) by composing a TextView instance within a TextShape and implementing TextShape in terms of TextView's interface. These two approaches correspond to the class and object versions of the Adapter pattern. TextShape an
Adapter pattern

This diagram shows how BoundingBox requests, declared in class Shape, are converted to GetExtent requests defined in TextView. Since TextShape adapts TextView to the Shape interface, the drawing editor can reuse the otherwise incompatible TextView class.

Often the
Adapter is responsible for functionality the adapted class doesn't provide. The diagram shows how an Adapter can fulfill such responsibilities. The user should be able to "drag" every Shape object to a new location interactively, but TextView isn't designed to do that. TextShape can add this missing functionality by implementing Shape's CreateManipulator operation, which returns an instance of the appropriate Manipulator subclass.

Catalog Structural Prev Next