java 插拔,如何在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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值