【问题标题】:In the implementation of my interface A I want to return an instance of type interface B在我的接口 A 的实现中,我想返回接口 B 类型的实例
【发布时间】:2017-03-19 03:02:12
【问题描述】:

这几天我一直在努力解决这个问题,我需要朝着正确的方向努力。

问题:

我正在尝试在我的网络应用程序中构建一个简单的登录系统。我正在努力做到这一点,以便我的类之间存在松散耦合。 我构建了两个接口;

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”。

如果是:返回 Authenticable 的实例。
如果没有:抛出 AuthenticationException。


但是,在我的 HardcodedAuthenticator 中,我不想局限于 Authenticable 的实现(至少这是我认为最好的),但我仍然希望能够返回 Authenticable 的实例。

问题:

接口A的实现Y如何返回接口B的实例?

提前非常感谢。
克里斯蒂安·阿德金

【问题讨论】:

  • 您的查询令人困惑..需要更多说明
  • 那么您希望Authenticable 的不同实现成为可能吗?您可以拥有一个setAuthenticable(Authenticable a),然后由该类使用,或者允许HardcodedAuthenticator 的子类覆盖默认实现。实现这种行为的策略或工厂方法/抽象工厂。
  • 混淆声明“但是在我的 HardcodedAuthenticator 中,我不想局限于 Authenticable 的实现(至少这是我认为最好的),但我仍然希望能够返回一个实例的 Authenticable..".
  • 如果我理解正确,将方法的方法返回类型更改为对象。或实现您希望返回其实例的所有接口。
  • 直到现在我还不清楚你的查询,但你的“接口 Authenticable”总是可以扩展其他接口,“HardcodedAuthenticator”总是可以实现其他接口。如果“Authenticable”扩展另一个接口“B”tehn,您可以将此方法的返回类型“authenticate”设置为“B”

标签: java oop design-patterns architecture solid-principles


【解决方案1】:

如果我正确理解您的问题您不希望您的 Authenticator 实现依赖于任何特定的 Authenticable 实现,您需要将 Authenticable 类型的引用注入到您的 Authenticator

        public interface Authenticator {
                  Authenticable authenticate(String username, char[] password,Authenticable authenticable) throws AuthenticationException;
       }

尝试做一些关于依赖注入的研究,如果你仍然对它感到困惑,你会发现很多有用的文章。

【讨论】:

  • 这正是我的问题的意思。这看起来是解决我的问题的好方法,我将研究依赖注入。
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 2013-07-22
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多