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)
请让我知道或建议好的编码设计模式。或者推荐任何参考书,以便我可以根据分析改进我的编码标准。提前致谢。
答案是:这取决于-取决于您的上下文/要求。
在创建 CommandLineOperation 实例时创建一次 ApiAccessor 的优点:
缺点:
但是当您考虑一下时:无论如何,这些缺点在现实世界中都不是什么大问题。
关于所需凭据来自解析文件的评论:归结为依赖注入!
本义:CommandLineOperation类应该不包含代码来构建一个ApiAccessor实例。该对象应该被注入(通过依赖注入框架)——或者例如通过构造函数提供。