gpt4 book ai didi

java - 泛型、接口(interface)谜题,这样声明接口(interface)有什么好处?

转载 作者:行者123 更新时间:2023-12-01 23:39:55 25 4
gpt4 key购买 nike

在我的项目中我看到这样的界面。所有模型都扩展了接口(interface)。我想知道有什么用?

public interface IModel {

<T> T modelTo(Class<T> clazz);
}

public interface IPerson extends IModel {

public String getFirstName();

public void setFirstName(String firstName);

public String getMiddleName();

public void setMiddleName(String middleName);

}

然后在代码中的某些地方我看到类似

@Override
public void modelJoin(IModel parent, IModel sample) {
//Some code
IPerson sample= sample.modelTo(IPerson.class);
IPerson person = parent.modelTo(IPerson.class);

//Some code

}

你能解释一下它的见解吗?

最佳答案

看起来像是 Adapter pattern 的使用。这个想法是为另一个类创建一个类的“ View ”,或者调整一种类来充当另一种类。

现实世界中一个简单的例子就是电源 socket 。不同的国家使用不同类型的 socket 。因此,您使用适配器将手机插入通常无法“识别”的电源 socket 。

这当然也可以使用面向对象编程和适配器模式来建模。使用您的 IModel 接口(interface),但将其命名为 IAdaptable,它可以像这样使用。

public interface IAdaptable {
<T> T adaptAs(Class<T> clazz);
}
public interface IChargeAmerican { void chargePhoneInAmerica(); }
public interface IChargeEurope { void chargePhoneInEurope(); }

public class EuropeanSocket implements IAdaptable, IChargeEurope {
public <T> T adaptAs(Class<T> clazz) {
if (clazz.equals(IChargeAmerican.class)) {
return new EuropeanSocketToAmericanSocketAdapter(this);
}
throw new RuntimeException("unknown");
}

public void chargePhoneInEurope() {
;
}
}

public class AmericanSocket implements IChargeAmerican {
public void chargePhoneInAmerica() {
;
}
}

public class EuropeanSocketToAmericanSocketAdapter implements IChargeAmerican {
private EuropeanSocket socket;
public EuropeanSocketToAmericanSocketAdapter(EuropeanSocket socket) {
this.socket = socket;
}

public void chargePhoneInAmerica() {
socket.chargePhoneInEurope();
}
}

要使用它,只需将欧洲 socket 适配为美国 socket ,有点像在两者之间插入适配器。

public void foo() {
EuropeanSocket europe = new EuropeanSocket();
IChargeAmerican murica = europe.adaptAs(IChargeAmerican.class);
murica.chargePhoneInAmerica();
}

此示例显示 AdaptAs 方法如何在 IChargeAmerican 和 IChargeEurope 两个接口(interface)之间创建链接。即使它们没有任何共同点,适配器也可以按照它们的方式行事。

现在,EuropeanSocket 实现了 IAdaptable 接口(interface),以便将自身“转换”为另一个已知的套接字。通常,类(class)不应该为此负责。正如维基百科上的示例所示,工厂或提供商更适合于此。

关于java - 泛型、接口(interface)谜题,这样声明接口(interface)有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com