Saturday, May 29, 2010

Adapter Pattern

    The Adapter pattern is a Structural pattern which allows us to provide a single interface between unrelated classes. There are two ways to do this: By extending the unrelated class or by using an object of the class within our class. The latter is called object composition. The former one is called as class adapter and the latter one is called as Object adapter.
    Lets see both these cases in the following example. Lets assume we have written a two Logger classes that log strings in a file and outputs on screen. 
ILogger.java
public interface ILogger
{
    public void log(String str);
}

FileLogger.java
public class FileLogger implements ILogger
{
    public void log(String str)
    {
        //write strings in file
    }
}
ConsoleLogger.java
public class ConsoleLogger implements ILogger
{
    public void log(String str)
    {
        //output strings to console
    }
}
Let us create our main class which makes use of the loggers. 
LoggerMain.java
public class LoggerMain
{
    public static void main(String[] str)
    {
        ILogger logger = null;
        if(type == FILE)
            logger = new FileLogger();
       else if(type == CONSOLE)
            logger = new ConsoleLogger();
        logger.log("Log string");
    }
}
    So far so good. Now suddenly, we get a requirement to log into the database. Fortunately, we have a third party class that does this efficiently. We really want to make use of it. The class is DBRecorder with a method recordString(String str). Obviously this class does not implement our interface. What can we do to include this class in our application? We can simply instantiate this class in our main method. But the reusability will get a hit and a small change will require a lot of coding effort and errors.
    So we create a adapter class which will solve the problem for us. The class is given below: 
DBLogger.java
public class DBLogger extends DBRecorder implements ILogger
{
    public void log(String str)
    {
        super.recordString(str);
    }
}
Now we can use this class in our main method with a simple addition like:
       if(type == DB)
           logger = DBLogger();
Simple. Isn't it? This is the whole point of adapter. The above class is an example of a class adapter.
What if your DBLogger need to extend from another class? We do not have multiple inheritance support in java. Object adapter comes to the rescue. We modify the class as follows to get the job done. 
DBLogger.java
public class DBLogger extends SomeClass implements ILogger
{
    public void log(String str)
    {
        DBRecorder recorder = new DBRecorder();
        recorder.recordString(str);
    }
}
The power of adapters are seen clearly in the above examples. In java, these adapters are simple to implement. To summarize, the main idea of Adapter is to 'make two unrelated classes work together'.

No comments:

Post a Comment