问题
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:
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);
}
}
来源:https://stackoverflow.com/questions/55574759/how-to-implement-pluggable-adapter-design-pattern-in-java