在阅读 Head First Design Patterns 中的类适配器模式时,我遇到了这句话:
class adapter... because you need multiple inheritance to implement it, which is not possible in Java
只是为了实验,我尝试了以下方法:
interface MyNeededInterface{
public void operationOne(MyNeededInterface other);
public MyNeededInterface operationTwo();
}
public class ThirdPartyLibraryClass{
public void thirdPartyOp();
}
假设我创建:
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);
}
}
在我的代码中,我可以使用:
MyNeededInterface myclass = createThirdPartyWrapper();
myclass.operationOne(someobj);
...
这不是类适配器模式吗?
最佳答案
类适配器模式在 Java 中是不可能的,因为您不能扩展多个类。因此,您必须采用使用组合而非继承的适配器模式。
可以在下面找到通过组合实现适配器模式的示例:
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();
}
}
现在您可以通过 TurkeyAdapter
将 Turkey
传递给需要 Duck
的方法。
class DuckCatcher
{
public void catch(Duck duck) { }
}
通过使用适配器模式,DuckCatcher
现在也能够捕获 Turkey(Adapter)
和 Duck
。
关于java - 在 Java 中实现类适配器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6305784/