在 Java 中实现类适配器模式 [英] Implementing Class Adapter Pattern in Java

查看:24
本文介绍了在 Java 中实现类适配器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 Head First Design Patterns 中的类适配器模式时,我来到了穿过这句话:

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

类适配器...因为你需要多重继承来实现它,这在Java中是不可能的

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();
}

假设我创建:

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?

推荐答案

类适配器模式在 Java 中是不可能的,因为您不能扩展多个类.因此,您必须使用使用组合而不是继承的适配器模式.

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();
    }
}

现在您可以通过 TurkeyAdapterTurkey 传递给需要 Duck 的方法.

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

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

通过使用适配器模式,DuckCatcher 现在也可以捕获 Turkey(Adapter)s 和 Ducks.

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

这篇关于在 Java 中实现类适配器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆