How to implement Pluggable Adapter design pattern in Java

时间:2019-04-08 13:36:37

标签: java design-patterns pluggable

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.

Thanks in advance.

1 个答案:

答案 0 :(得分:1)

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

在Java中,这种事情非常容易,但是没有涉及到的对象实际上与您可能在C#中使用的可插入适配器对象相对应。

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

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

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)
    {
        ...
    }
}

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

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