Adapter pattern

The adapter pattern, as the name suggests, is the pattern for a class that adapts the interface of another considerably complicated or inconsistent class. It's basically just a wrapper class. It wraps the interface of another class to an interface that is simpler, consistent to the software design, and is what the client is expecting.

The following diagram shows the adapter pattern in general and the one used for our example:

It is one of the simplest GoF design patterns with the purpose of simplifying the interface.

In the example scenario, we have an Oracle database hypothetical DB driver class with a complex and inconsistent API interface in contrast to our own application design. Therefore, in order to simplify things and make them uniform to use in our application, we define our adapter interface, which our client code will use to access the actual database objects without knowing the details of how to use Oracle DB driver.

Let's take a look at our imaginary code. The following is our hypothetical and not-so-simple OracleDBDriver interface:

    public interface OracleDBDriver 
{
bool Initialize(string parameters);

IOracleDBConnection CreateNewConnection();
IOracleDBConnection CreateNewPooledConnection();

bool ValidateSQL(string validSQL);

SomeDBFormat ExecuteSQL(IOracleDBConnection dbCon,
string validSQL);
int ExecuteScalarSQL(IOracleDBConnection dbCon, string
validSQL);
}

To simply the interface of OracleDBDriver, we write our simplified adapter, as shown here:

    public class DBAdapter 
{
private OracleDBDriver dbDriver = null;
private bool bDBInitialized;
private readonly string initializationDBParameters;

public DBAdapter()
{
//dbDriver = new OracleDBDriverImpl();
initializationDBParameters = "XYZ, ABC";
}

public DataTable ExecuteSQL(string strSQL)
{
if (string.IsNullOrWhiteSpace(strSQL)) throw new
InvalidSQLException();

if (!bDBInitialized) bDBInitialized =
dbDriver.Initialize(initializationDBParameters);

if(!dbDriver.ValidateSQL(strSQL)) throw new
InvalidSQLException();

var dbConnection = dbDriver.CreateNewPooledConnection();

SomeDBFormat dbData = dbDriver.ExecuteSQL(dbConnection,
strSQL);

return TransformDBDataType(dbData);
}

private DataTable TransformDBDataType(SomeDBFormat dbData)
{
DataTable dbTable = null;

//dbTable = dbData; do some conversions

return dbTable;
}
}

From the preceding code, you can easily see how our adapter class is hiding the complexity of database driver initialization and connection pooling logic as well as transforming the db format into a simplified one, as desired.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.68.159