Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Class Adapter Pattern in Java

While reading up on the Class Adapter pattern in Head First Design Patterns, I came across this sentence:

class adapter... because you need multiple inheritance to implement it, which is not possible in Java

Just to experiment, I tried the following:

interface MyNeededInterface{
    public void operationOne(MyNeededInterface other);
    public MyNeededInterface operationTwo();
}

public class ThirdPartyLibraryClass{
    public void thirdPartyOp();
}

Suppose I create :

class ThirdPartyWrapper extends ThirdPartyLibraryClass implements MyNeededInterface{

    @Override
    public void operationOne(ThirdPartyWrapper other){
        this.thirdPartyOp();
        dosomeExtra();
    }
    @Override
    public ThirdPartyWrapper operationTwo(){
        int somevalue = doSomeThingElse();
        return new ThirdPartyWrapper(somevalue);
    }
}

In my code, I can use:

MyNeededInterface myclass = createThirdPartyWrapper();
myclass.operationOne(someobj);
...

Is this not the Class Adapter pattern?

like image 445
markjason72 Avatar asked Jun 10 '11 11:06

markjason72


People also ask

What is Adapter pattern in Java?

An Adapter pattern acts as a connector between two incompatible interfaces that otherwise cannot be connected directly. An Adapter wraps an existing class with a new interface so that it becomes compatible with the client's interface.

Where can you implement Adaptors?

In design, adapters are used when we have a class (Client) expecting some type of object and we have an object (Adaptee) offering the same features but exposing a different interface.


1 Answers

The class adapter pattern is not possible in Java because you can't extend multiple classes. So you'll have to go with the adapter pattern which uses composition rather than inheritance.

An example of the adapter pattern through composition can be found below:

interface Duck
{
    public void quack();
}

class BlackDuck implements Duck
{
   public void quack() { }
}

class Turkey
{
    public void gobble() { }
}

class TurkeyAdapter implements Duck
{
    private Turkey t;

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

    public void quack()
    {
        // A turkey is not a duck but, act like one
        t.gobble();
    }
}

Now you can pass a Turkey to a method which is expecting a Duck through the TurkeyAdapter.

class DuckCatcher
{
    public void catch(Duck duck) { }
}

By using the adapter pattern the DuckCatcher is now also able to catch Turkey(Adapter)s and Ducks.

like image 178
Kevin Avatar answered Sep 29 '22 21:09

Kevin