Geeks With Blogs
A Curious Mind #tastic

To me the adapter pattern is all about bringing someone elses code API into line with your Domain model. Their API may be a beautiful API but that doesn't mean that their concerns will match your concerns in the right way. Of course their API could be so clueless that the only to make sense of it is to hide it behind another class. These are both usage of the adapter pattern.

Another benefit of the Adapter pattern is that it can keep your code decoupled from third-party code. By providing a wrapper around say log4net you can easily switch later to NLog should it be necessary, by just changing the internals of the adapter class.

public class LoggingAdapter //log4net
{
    ILog log = log4net.LogManager.GetLogger("MyApp"); //1
    
    public static void Log(string message)
    {
        log.Info(message);
    }
}

public class LoggingAdapter //NLog
{
    Logger log = NLog.LogManager.GetCurrentClassLogger(); //1
    
    public static void Log(string message)
    {
        log.Info(message);
    }
}

So the interface of the LoggingAdapter didn't change at all, so we won't have to go and change our code at all except at the commented //1 locations. How cool is that?

Portland Repository

Wikipedia

Posted on Tuesday, August 22, 2006 12:55 PM | Back to top


Comments on this post: Adapter Pattern

# re: Adapter Pattern
Requesting Gravatar...
Hey Dru,

Caught your presentation yesterday. You did a good job.

On this pattern I think you might consider using an Interface instead of a class. In the code that would use the class you use the interface instead. Then you would not have to rewrite the class but just change which class is being used (especially handy if you switch from one logger to the next then back again).
Then you could use the Factory pattern to have the code determine which class to use.

That's what I think anyway...I could be wrong.
Left by Mark Flory on Aug 23, 2006 11:41 AM

# re: Adapter Pattern
Requesting Gravatar...
Mark, I whole heartedly agree with using an interface. However, in the presentation I was trying to keep things as simple as possible. But you are right. In my code as well I would have used an interface. I will make sure to add that to the presentation. Thank you.
Left by Dru on Aug 23, 2006 2:31 PM

Your comment:
 (will show your gravatar)


Copyright © Dru Sellers | Powered by: GeeksWithBlogs.net