[英]How to implement Pluggable Adapter design pattern in Java
我知道如何實現基本的適配器設計模式,也知道 C# 如何使用委托來實現可插拔適配器設計。 但是我找不到任何用 Java 實現的東西。 你介意指出一個示例代碼。
提前致謝。
可插拔適配器模式是一種創建適配器的技術,它不需要為您需要支持的每個適配器接口創建一個新類。
在 Java 中,這種事情非常簡單,但不涉及任何實際對應於您可能在 C# 中使用的可插拔適配器對象的對象。
許多適配器目標接口是功能接口——只包含一種方法的接口。
當您需要將此類接口的實例傳遞給客戶端時,您可以使用 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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.