如何在Java中实现可插拔适配器设计模式 [英] How to implement Pluggable Adapter design pattern in Java

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

问题描述

我知道如何实现基本的适配器设计模式,也知道C#如何使用委托来实现可插拔适配器设计。但是我找不到用Java实现的任何东西。

I know how to implement basic Adapter design pattern and also knows how C# using delegation to implement Pluggable Adapter design. But I could not find anything implemented in Java. Would you mind pointing out an example code.

预先感谢。

推荐答案

可插拔适配器模式是一种用于创建适配器的技术,不需要为需要支持的每个适配器接口创建新类。

The pluggable adapter pattern is a technique for creating adapters that doesn't require making a new class for each adaptee interface you need to support.

在Java中,事情超级简单,但实际上并没有涉及您可能在C#中使用的可插入适配器对象的对象。

In Java, this sort of thing is super easy, but there isn't any object involved that would actually correspond to the pluggable adapter object you might use in C#.

许多适配器目标接口都是功能接口-仅包含一种方法的接口。

Many adapter target interfaces are Functional Interfaces -- interfaces that contain just one method.

当您需要将此类接口的实例传递给客户端时,可以使用lambda函数或方法参考轻松地指定适配器。例如:

When you need to pass an instance of such an interface to a client, you can easily specify an adapter using a lambda function or method reference. For example:

interface IRequired
{
   String doWhatClientNeeds(int x);
}

class Client
{
   public void doTheThing(IRequired target);
}

class Adaptee
{
    public String adapteeMethod(int x);
}

class ClassThatNeedsAdapter
{
    private final Adaptee m_whatIHave;

    public String doThingWithClient(Client client)
    {
       // super easy lambda adapter implements IRequired.doWhatClientNeeds
       client.doTheThing(x -> m_whatIHave.adapteeMethod(x));
    }

    public String doOtherThingWithClient(Client client)
    {
       // method reference implements IRequired.doWhatClientNeeds
       client.doTheThing(this::_complexAdapterMethod);
    }

    private String _complexAdapterMethod(int x)
    {
        ...
    }
}

当目标接口具有多个方法时,我们使用匿名内部类:

When the target interface has more than one method, we use an anonymous inner class:

interface IRequired
{
   String clientNeed1(int x);
   int clientNeed2(String x);
}

class Client
{
   public void doTheThing(IRequired target);
}


class ClassThatNeedsAdapter
{
    private final Adaptee m_whatIHave;

    public String doThingWithClient(Client client)
    {
       IRequired adapter = new IRequired() {
           public String clientNeed1(int x) {
               return m_whatIHave.whatever(x);
           }
           public int clientNeed2(String x) {
               return m_whatIHave.whateverElse(x);
           }
       };
       return client.doTheThing(adapter);
    }
}

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

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