在我的接口 A 的实现中,我想 return 类型接口 B 的实例
In the implementation of my interface A I want to return an instance of type interface B
几天来我一直在努力解决这个问题,我需要朝着正确的方向推动一下。
问题:
我正在尝试在我的网络应用程序中构建一个简单的登录系统。我试图做到这一点,以便我的 类 之间存在松耦合。
我建立了两个接口;
public interface Authenticable {
String getUsername();
boolean changePassword(char[] password);
}
该接口将由类实现,可认证
public interface Authenticator {
Authenticable authenticate(String username, char[] password) throws AuthenticationException;
}
并且这个接口将由类实现,可以验证一个Authenticable。
目前我没有数据库或任何东西,但我决定我希望能够先构建一个简单的 Authenticator,然后再将其换成另一个(可能使用数据库或文件系统) .
所以我做的第一个实现是:
public class HardcodedAuthenticator implements Authenticator {
@Override
public Authenticable authenticate(String username, char[] password) throws AuthenticationException {
if (username == "test" && password == new char[]{'t', 'e', 's', 't'}) {
}
}
}
此实现仅检查用户名是否等于 'test' 且密码是否等于 'test'。
如果是:Return Authenticable 的实例。
如果没有:抛出 AuthenticationException。
但是在我的 HardcodedAuthenticator 中,我不想局限于 Authenticable 的实现(至少我认为这是最好的)但我仍然希望能够 return Authenticable 的一个实例..
问题:
接口A的实现Y如何return接口B的实例?
非常感谢。
克里斯蒂安·阿德金
如果我正确理解你的问题你不希望你的 Authenticator 实现依赖于 Authenticable 的任何特定实现,你需要将 Authenticable 类型的引用注入你的 Authenticator
public interface Authenticator {
Authenticable authenticate(String username, char[] password,Authenticable authenticable) throws AuthenticationException;
}
尝试做一些关于依赖注入的研究,如果你仍然对它感到困惑,你会发现很多有用的文章。
几天来我一直在努力解决这个问题,我需要朝着正确的方向推动一下。
问题:
我正在尝试在我的网络应用程序中构建一个简单的登录系统。我试图做到这一点,以便我的 类 之间存在松耦合。 我建立了两个接口;
public interface Authenticable {
String getUsername();
boolean changePassword(char[] password);
}
该接口将由类实现,可认证
public interface Authenticator {
Authenticable authenticate(String username, char[] password) throws AuthenticationException;
}
并且这个接口将由类实现,可以验证一个Authenticable。
目前我没有数据库或任何东西,但我决定我希望能够先构建一个简单的 Authenticator,然后再将其换成另一个(可能使用数据库或文件系统) .
所以我做的第一个实现是:
public class HardcodedAuthenticator implements Authenticator {
@Override
public Authenticable authenticate(String username, char[] password) throws AuthenticationException {
if (username == "test" && password == new char[]{'t', 'e', 's', 't'}) {
}
}
}
此实现仅检查用户名是否等于 'test' 且密码是否等于 'test'。
如果是:Return Authenticable 的实例。
如果没有:抛出 AuthenticationException。
但是在我的 HardcodedAuthenticator 中,我不想局限于 Authenticable 的实现(至少我认为这是最好的)但我仍然希望能够 return Authenticable 的一个实例..
问题:
接口A的实现Y如何return接口B的实例?
非常感谢。
克里斯蒂安·阿德金
如果我正确理解你的问题你不希望你的 Authenticator 实现依赖于 Authenticable 的任何特定实现,你需要将 Authenticable 类型的引用注入你的 Authenticator
public interface Authenticator {
Authenticable authenticate(String username, char[] password,Authenticable authenticable) throws AuthenticationException;
}
尝试做一些关于依赖注入的研究,如果你仍然对它感到困惑,你会发现很多有用的文章。