Adapter Design Pattern

This design pattern is pretty easy to use and understand, so this article is going to be short. First of all, why do we need it at all? Well, the main reason is the following – there are some classes that might implement useful algorithms, but we expect a bit different output out of them. For instance:
1) Legacy shape uses top left coordinates, and then height and width for rectangle. We would like to use top left and bottom left coordinates knowing we are talking about rectangle initially.
2) We have old customer authentication interface which expects different type of Customer class that we use.

In other words, there are lots of reasons why Adapter can and should be used. I will give a sketch of real-world example for the customer authentication. Let us say that old authentication API uses the following class for Customer:

public class APICustomer {
    public Email { get; set; }
    public Password { get; set; }

And we use the following class:

public class Customer {
    public UserName { get; set; }
    public Password { get; set; }

And now we need some adapter that adapts our Customer to APICustomer. We can implement it in the following way:

public class CustomerAdapter {
    public static APICustomer Adapt(Customer c) {
        // Given the circumstances that all users use as email domain.
        // In the Gmail users' database it might actually be so. However, in a more real-world adoption of APICustomer would be much more difficult or even impossible.
        // Still, this is not a bad example to illustrate use of it.
        return new APICustomer { Email = c.UserName + "", Password = c.Password };

And this is it. Basically, I have introduced a pretty simple class that converts object of Customer to APICustomer object. In other words, it means that Adapter does not have any sort of strict obligations regarding use of it, so Adapter might be almost everything that you use everyday in your programming life. Just think about it.

Leave a Reply

Your email address will not be published. Required fields are marked *