In software engineering, the adapter pattern is a software design pattern (also known as wrapper, an alternative naming shared with the decorator pattern) that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
An example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed.
The adapter design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
The adapter design pattern solves problems like:
- How can a class be reused that does not have an interface that a client requires?
- How can classes that have incompatible interfaces work together?
- How can an alternative interface be provided for a class?
Often an (already existing) class can't be reused only because its interface doesn't conform to the interface clients require.
The adapter design pattern describes how to solve such problems:
- Define a separate
adapter
class that converts the (incompatible) interface of a class (adaptee
) into another interface (target
) clients require. - Work through an
adapter
to work with (reuse) classes that do not have the required interface.
The key idea in this pattern is to work through a separate adapter
that adapts the interface of an (already existing) class without changing it.
Clients don't know whether they work with a target
class directly or through an adapter
with a class that does not have the target
interface.
See also the UML class diagram below.
An adapter allows two incompatible interfaces to work together. This is the real-world definition for an adapter. Interfaces may be incompatible, but the inner functionality should suit the need. The adapter design pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.
An adapter can be used when the wrapper must respect a particular interface and must support polymorphic behavior. Alternatively, a decorator makes it possible to add or alter behavior of an interface at run-time, and a facade is used when an easier or simpler interface to an underlying object is desired.
Pattern | Intent |
---|---|
Adapter or wrapper | Converts one interface to another so that it matches what the client is expecting |
Decorator | Dynamically adds responsibility to the interface by wrapping the original code |
Delegation | Support "composition over inheritance" |
Facade | Provides a simplified interface |
In the above UML class diagram, the client
class that requires (depends on) a target
interface cannot reuse the adaptee
class directly because its interface doesn't conform to the target
interface. Instead, the client
works through an adapter
class that implements the target
interface in terms of adaptee
:
- The
object adapter
implements thetarget
interface by delegating to anadaptee
object at run-time (adaptee.specificOperation()
). - The
class adapter
implements thetarget
interface by inheriting from anadaptee
class at compile-time (specificOperation()
).
In this adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped object.
This adapter pattern uses multiple polymorphic interfaces implementing or inheriting both the interface that is expected and the interface that is pre-existing. It is typical for the expected interface to be created as a pure interface class, especially in languages such as Java (before JDK 1.8) that do not support multiple inheritance of classes.
OCL HELPPPP!!!!
PLEASE HELP MEEE!!!!
class Reservation < Booking
-- overrides booking
attributes
arrivalTime : TimeDate
operations
setArrivalTime(td : TimeDate)
begin
self.td := td
end
end
class Booking
attributes
covers : Integer
td : TimeDate
table : Table
operations
getTimeDate(td : TimeDate)
getDetails()
getCovers(c : Integer)
setArrivalTime(td : TimeDate)
setTable(t : Table)
end
This problem is typical of the situations faced by designers, and a lot of work has been put into documenting solutions to common design problems as design patterns. In this case, a suitable solution is provided by the Observer pattern defined in the influential book by Gamma et al. (1995). The definition of this pattern states that it is applicable:
- ‘When a change to one object requires changing others, and you don’t know how many objects need to be changed.
- When an object should be able to notify other objects without making assumptions about who those objects are.’
The present situation contains elements of both these conditions: we want a change in an application object to be followed by a change in the view object, and we want the application object to be able to notify the view object of this change without being dependent on the view object. The definition of the pattern is rather abstract and in this section only its application will be described.
The application of the Observer pattern to allow display updating in the restaurant booking system is shown in Figure in the question and the packages representing the different layers in the application are also shown. Notice that the relationships between classes that cross the package boundaries are consistent with the direction of the dependency between the two layers.
As with many patterns, the solution of the problem depends on polymorphism and dynamic binding. In the application layer, an interface is defined that must be implemented by any class that wishes to be informed about relevant changes to the model. Such classes are known as observers. The interface is very simple, consisting of a single operation, which can be called whenever the display needs to be updated. The booking system class maintains references to a set of observers and, when its state changes, sends the ‘update’ message to each observer. The observers could be of any class whatsoever, but the booking system only accesses them through this interface, defined in the application layer, so that the layered architecture of the system is preserved.
The ‘StaffUI’ class in the presentation layer implements the ‘BookingObserver’ interface. Implementation of an interface is depicted in UML by a dashed arrow with a hollow arrowhead, as shown in Figure in the question. At system start-up, an instance of ‘StaffUI’ can be added to the booking system’s list of observers by means of the ‘addObserver’ operation. Once this is done, the ‘update’ messages sent to the list of observers will be received by the ‘StaffUI’ object, thanks to dynamic binding.
Once a ‘StaffUI’ object receives an ‘updateDisplay’ message, it needs to find out what has changed. Initially, we will assume a very simple approach to this, where the boundary object simply requests from the booking system a list of all the bookings that are to be displayed and then completely refreshes the display. This rudimentary approach can be refined later if it turns out to be a performance issue. Figure below shows the interactions that take place when the display is actually updated. In general, there will be more than one observer: the ‘notifyObservers’ operation in the ‘BookingSystem’ class simply sends the ‘update’ message to each, and so it replaces the ‘updateDisplay’ message in diagrams.
Compared with the class diagram in Figure in the question, on Figure below it looks as if the booking system and user interface objects are communicating directly with each other, and hence that an application object is dependent on an object in the presentation layer. Although the objects are communicating, however, this is only in virtue of the fact that the user interface object implements the observer interface shown in Figure in the question. This is emphasized in the Figure below by adding a role name to the boundary object.
In the context of the Figure below, it is probably also worth restating the responsibilities of the various objects: having a good grasp of these makes it easier to understand why the messages are the way they are. The user’s request is for the bookings for a particular day to be displayed. This request is passed to the booking system object. The booking system only has the responsibility to record information about the day currently being displayed: assuming that the user has requested a different date, the information for that date must first be retrieved from the restaurant object, whose responsibility is to maintain information about all the bookings known to the system. The user interface object’s responsibility is simply to display a set of bookings, and it must request from the booking system the date and the set of bookings to display. We are not assuming that the user interface remembers these bookings, though there are potential performance improvements to be made in the future by having it cache some information about the bookings.
Check diagram below
-
assertions useful with polymorphism, assertions can help keep subclass operations consistent with those of superclass
-
invariants and post-conditions must be true for all subclasses, subclass can strengthen these i.e. make them more restrictive
-
not allowed to strengthen preconditions – because of substitutability, can only weaken a precondition
-
if a subclass strengthened a pre-condition, then a superclass operation could fail when applied to instance of subclass
-
preconditions: best pay-off for least overhead
-
one language to support assertions is Eiffel
In class we have already looked at the role of design by contract (DbC) in software specification. We examined the notions of weakening the pre-condition and strengthening the post-condition in cases of polymorphism and inheritance.
Sequence Diagram