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?
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.
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.
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 Duck
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With