It helps two incompatible interfaces to work together.
Real Work Example
Figure 1: A real world example of Adapter Design Pattern. By using an adapter you can use the rounded corner socket.
Software Engineering Examples
- ADO.Net SqlAdapter
- MySqlAdapter
- OracleAdapter
- We want to allow two classes to work together.
- When we don't want to break clients that are using the adaptee class. This very important in api that has several versions;
- We want preserve Open/Close Principle;
- When we are using third party api and we can't edit the codes;
- When we want to extend the functionality of existing class.
Participants
Class/Interface | Description |
---|---|
ITarget | An interface defines the properties and methods to be implemented by the Adapter. |
Adapter | A concrete class that ITarget interface. It handles communication between the client and the adaptee. |
Adaptee | This contains the functionality but it can be use by client because it's incompatible. The existing class. |
Client | It uses/consumes the adaptee through the adapter. |
Sample Implementation
This is a sample application that uses Adapter Design Pattern to allow a legacy code to be use by client that uses strongly type variables. We can call this Book Order application.
The legacy code reads and parse xml files (books ordered) and stores it arraylist then finally gives to a client that uses it. We want the result to be strongly type because arrays are difficult to handle. Adaper Design Pattern solves this problem.
The Project Structure
The BookOrder.xml is stored in bin/debug folder.
UML Class Diagram
The legacy code reads and parse xml files (books ordered) and stores it arraylist then finally gives to a client that uses it. We want the result to be strongly type because arrays are difficult to handle. Adaper Design Pattern solves this problem.
The Project Structure
The BookOrder.xml is stored in bin/debug folder.
UML Class Diagram
Mapping
Adapter Design Pattern | Book Order |
---|---|
ITarget | IGetBookOrder |
Adapter | BookOrder |
Adaptee | GetXMLBookOrder |
Client | Program |
The Order class is use for storing data.
The Codes
The POCO
Order.cs
The Adapter
IGetBookOrder.cs
BookOrder.cs
The Adaptee
GetXMLBookOrder.cs
The Client
Program.cs
The Output
Hope this is helpful. Thanks for viewing. Your thoughts!