Class and Object Adapter

The Adapter Pattern converts the interface of a class in another interface, to match the requirements of a client class. In this way an Adapted helps classes to work together even though they were not designed for that, and they don't have compatible interfaces.

In the Object Adapter Pattern, the Client expects a Target interface, providing a request() method. So the Adapter implements that interface and it is composed with the Adaptee class. The request() in the Adapter would use specific methods of the Adaptee class to perform its duty.

The Class Adapter Pattern makes use of Multiple Inheritance, and so it can't be used if Java is our implementation language. The difference is that we don't design the Adaptor class to have internally a reference to an Adaptee object, but it would actually derive publicly from it.

I have written this post while I was reading the first part of chapter seven of Head First Design Patterns, there you would find more information on the matter.

The example for the Adapter Patter is based on a change request for our system that emulates ducks quacking and flying. Now we want to adapt turkeys to be used instead ducks for the same tasks.

We have an existing Duck hierarchy:
public interface Duck {
    public void quack();
    public void fly();
}

public class DuckMallard implements Duck {
    public void quack() {
        System.out.println("quack!");
    }

    public void fly() {
        System.out.println("flying");
    }
}
And we have a different bird that we want to use as it would be a duck:
public interface Turkey {
    public void gobble();

    public void shortFly();
}
To do that we use this turkey adapter:
public class TurkeyAdapter implements Duck {
    Turkey turkey;

    public TurkeyAdapter(Turkey turkey) {
        this.turkey = turkey;
    }

    public void quack() {
        turkey.gobble();
    }

    public void fly() {
        for(int i = 0; i < 5; ++i)
            turkey.shortFly();
    }
}
This short function accepts in input a duck and makes it flying and quacking:
static void testDuck(Duck d) {
    d.fly();
    d.quack();
}

Here is a few lines of a tester for the adapter:
Duck duck = new DuckMallard();
Turkey turkey = new TurkeyWild();
Duck duckFake = new TurkeyAdapter(turkey);

System.out.println("Duck:");
testDuck(duck);

System.out.println("Turkey:");
turkey.shortFly();
turkey.gobble();

System.out.println("Turkey faking a duck:");
testDuck(duckFake);

No comments:

Post a Comment