Adapter Design Pattern: Target Adapter Adaptee Client
Adapter Design Pattern: Target Adapter Adaptee Client
Adapter Design pattern Definition Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. Discussion An adapter class implements an interface known to its clients and provides access to an instance of a class not known to its clients. Adapter pattern is basically used to convert the programming interface of one class into that of another. There are two ways to do this: by inheritance and by object composition. In the first case, a new class is derived from the nonconforming one and the methods are added to make the new derived class match the desired interface. The other way is to include the original class inside the new one and create the methods to translate calls within the new class. These two approaches, called class adapters & object adapters, are both fairly easy to implement. The adapter pattern allows us to fit new elements into our design without compromising it. By creating adapters, we preserve our designs integrity and dont let low-level details or a clunky interface leak out and affect other objects UML class diagram
participants The classes and/or objects participating in this pattern are: Target o defines the domain-specific interface that Client uses. Adapter o adapts the interface Adaptee to the Target interface. Adaptee o defines an existing interface that needs adapting. Client o collaborates with objects conforming to the Target interface.
2
Example DataAdapter class in .NET Framework represents a set of data commands and a database connection that are used to fill the DataSet and update the data source. The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and update that changes the data in the data source to match the data in the DataSet. .NET framework (ver 1. 1 and ver 2.0) has implementations of the following data adapters: SqlDataAdapter ,OledbDataAdapter,OdbcDataAdapter andOracleDataAdapter The SqlDataAdapter serves as a bridge between a DataSet and SQL Server for retrieving and saving data. The following code snippet creates an instance of a DataAdapter that uses a connection to the SQL Server Northwind database and populates the DataSet with the list of employees. using (SqlConnection connection = new SqlConnection(connectionString)) // connectionString retrieves the connection string from a configuration file { SqlDataAdapter adapter = new SqlDataAdapter(select * from employees, connection); DataSet ds = new DataSet(); Adapter.Fill(ds, Employees); } In the above example we have Adaptee - Data Source (SQL Server) Target - DataSet Adapter - SqlDataAdapter Target Method - Fill (Dataset instance)