クラスにビルダーパターンを使用しようとしています..
以下は、Effective Java, 2nd Edition で示した Joshua Bloch バージョンに従って作成した Builder クラスです。私たちの顧客はほとんどの場合userId
、clientId
常に合格しますが、他のフィールドはオプションであり、合格する場合としない場合があります。ここで、Preference は 4 つのフィールドを持つ ENUM クラスです。
public final class InputKeys {
private long userid;
private long clientid;
private long timeout = 500L;
private Preference pref;
private boolean debug;
private Map<String, String> parameterMap;
private InputKeys(Builder builder) {
this.userid = builder.userId;
this.clientid = builder.clientId;
this.pref = builder.preference;
this.parameterMap = builder.parameterMap;
this.timeout = builder.timeout;
this.debug = builder.debug;
}
public static class Builder {
protected final long userId;
protected final long clientId;
protected long timeout;
protected Preference preference;
protected boolean debug;
protected Map<String, String> parameterMap;
public Builder(long userId, long clientId) {
this.userId = userId;
this.clientId = clientId;
}
public Builder parameterMap(Map<String, String> parameterMap) {
this.parameterMap = parameterMap;
return this;
}
public Builder preference(Preference preference) {
this.preference = preference;
return this;
}
public Builder debug(boolean debug) {
this.debug = debug;
return this;
}
public Builder timeout(long timeout) {
this.timeout = timeout;
return this;
}
public InputKeys build() {
return new InputKeys(this);
}
}
}
以下は私のENUMクラスです-
public enum Preference {
PRIMARY,
SECONDARY
}
パラメータを構築するためにこのような呼び出しを行っていInputKeys
ます-
InputKeys keys = new InputKeys.Builder(12000L, 33L).build();
System.out.println(keys);
ここで私が見ている唯一の問題は、顧客がタイムアウト値を渡していない場合、デフォルトのタイムアウト値を常に 500 に設定する必要がありますが、顧客がタイムアウト値を渡している場合は、デフォルトのタイムアウト値を上書きする必要があることです。そして、これは私にとってはうまくいきません。なぜなら、デバッグ モードで私のものを見ると、keys
常にタイムアウト値が 0 になるからです。
不足しているものはありますか?また、このクラスを不変でスレッド セーフにしようとしています。
アップデート:-
人々がこれを使用する特定のシナリオは、顧客が私たちのコードを呼び出すために使用するファクトリです。keys
クラスの1つがそれを実装している単純なインターフェースがあり、次に、このパラメーター を受け入れるその実装の特定のメソッドを呼び出すファクトリがあります。
そのため、アプリケーションで以下のコードを使用して呼び出しを行い、マルチスレッド環境でアプリケーションを実行する可能性があります。
InputKeys keys = new InputKeys.Builder(12000L, 33L).build();
IClient client = ClientFactory.getInstance();
client.getData(keys);
そして、InputKeys Builder を複数回使用してキーを作成できます。これは 1 回だけではありません。取得する userId と clientId が何であれ、InputKeys を再度構築します。