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?
解决方案
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.