我有一个如下的Builder类,但是我不知道这是使该类具有 Singleton 行为并保持我的 Builder 模式不变的正确方法时间。使用一些“单元素枚举类型”?或某些recommended方式?
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public class ClientMailAdapter {
public static ClientMailAdapter.WebLiteRequestBuilder builder() {
return new ClientMailAdapter.WebLiteRequestBuilder();
}
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class WebLiteRequestBuilder {
private Map<String, String> parameters;
private String username;
private String password;
private Source source;
public ClientMailAdapter.WebLiteRequestBuilder parameters(final Map<String, String> parameters) {
this.parameters = parameters;
return this;
}
public ClientMailAdapter.WebLiteRequestBuilder username(final String username) {
this.username = username;
return this;
}
public ClientMailAdapter.WebLiteRequestBuilder password(final String password) {
this.password = password;
return this;
}
public ClientMailAdapter.WebLiteRequestBuilder source(final Source source) {
this.source = source;
return this;
}
public ClientMailResult sendEmail() {
return new ClientMailService().sendEmailXML(
ClientRequest.builder()
.username(username)
.password(password)
.parameters(parameters)
.source(source)
.build());
}
}
@AllArgsConstructor
@Getter
public enum Source {
XXXXX("Source Name To Be Defined X");
private final String name;
}
}
答案 0 :(得分:0)
我不确定这是否是您要尝试的操作,但是可以这样:也许您需要将单例与构建器分开。通过编写具有单个值的枚举,以标准方式创建单例。但是,代替构建器类,创建一个配置器类,该类具有设置单例选项的权限。它们应该位于同一个程序包中,因此您可以将设置器中的设置器保持为只能由配置器访问。如果只构建一次,就不需要构建器。那是你的主意吗?