简体   繁体   中英

How to implement Pluggable Adapter design pattern in 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.

Thanks in advance.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM