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

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

问题描述

首要设计模式中阅读类适配器模式时,我来了在这个句子中:

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

现在您可以传递土耳其到希望 Duck 通过 TurkeyAdapter 的方法。

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 土耳其(适配器) s和 Duck s。

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

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

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