使用实例成员的编码模式

Sub*_*dal 5 java design-patterns

假设我有一个名为CommandLineOperation. 此类访问 API 资源。因此我定义了一个 type 的实例成员APIAccessor

class CommandLineOperation {
    APIAccessor apiAccessor;
    void create() {
        apiAccessor = new APIAccessor(email,password);
        //do work for creation
    }
    void update() {
        apiAccessor = new APIAccessor(email,password);
        //do work for update
    }
}

class APIAccessor {
    String email;
    String password;
    APIAccessor(email,password) {
        this.email = email;
        this.password = password;
    }
}
Run Code Online (Sandbox Code Playgroud)

CommandLine 中的操作不常见,APIAccessor在每个操作下实例化或使用CommandLineOperation类的构造函数创建一次是更好的方法。例如

CommandLineOperation(String email,String password) {
    this.apiAccessor = new APIAccessor(email,password);
}
Run Code Online (Sandbox Code Playgroud)

请让我知道或建议好的编码设计模式。或者推荐任何参考书,以便我可以根据分析改进我的编码标准。提前致谢。

Gho*_*ica 5

答案是:这取决于-取决于您的上下文/要求。

在创建 CommandLineOperation 实例时创建一次 ApiAccessor 的优点:

  • 然后您可以创建不可变对象(通过使该字段成为最终对象)。这有很多优点——因为你总是知道这个字段是初始化的(理想情况下,你甚至可能想要验证 ApiAccessor 实际上是有效的并且不包含错误的信息)
  • 您的其他方法可以专注于他们的直接责任 - 而不是担心该字段是否已经初始化
  • 因此,单元测试也更容易-在您需要嘲讽的情况下,你只需要提供一个ApiAccessor对象一次-而不是用它每次处理调用的CommandLineOperation的“真实”的方法之一

缺点:

  • 您不能为给定的 CommandLineOperation 对象“切换”ApiAccessor
  • 如果你有数以百万计的这些对象闲逛而不是你的,你会浪费一些记忆

但是当您考虑一下时:无论如何,这些缺点在现实世界中都不是什么大问题。

关于所需凭据来自解析文件的评论:归结为依赖注入!

本义:CommandLineOperation类应该包含代码来构建一个ApiAccessor实例。该对象应该被注入(通过依赖注入框架)——或者例如通过构造函数提供。