gpt4 book ai didi

java - 如何确保我的 map 在我的构建器模式中设置后永远不会被修改?

转载 作者:行者123 更新时间:2023-11-29 05:07:04 27 4
gpt4 key购买 nike

下面是我在我的一个项目中使用的构建器模式,我想让它在多线程环境中是线程安全的。一旦 ClientKey 被设置,我不希望任何人再次修改它。

public final class ClientKey {

private final long userId;
private final int clientId;
private final long timeout;
private final boolean dataFlag;
// how can I make sure that my parameterMap is never modified once set
private final Map<String, String> parameterMap;

private ClientKey(Builder builder) {
this.userId = builder.userId;
this.clientId = builder.clientId;
this.remoteFlag = builder.remoteFlag;
this.dataFlag = builder.dataFlag;
this.parameterMap = builder.parameterMap;
this.timeout = builder.timeout;
}

public static class Builder {
protected final long userId;
protected final int clientId;
protected long timeout = 200L;
protected boolean remoteFlag = false;
protected boolean dataFlag = true;
protected Map<String, String> parameterMap;

public Builder(long userId, int clientId) {
this.userId = userId;
this.clientId = clientId;
}

public Builder parameterMap(Map<String, String> parameterMap) {
this.parameterMap = parameterMap;
return this;
}

public Builder remoteFlag(boolean remoteFlag) {
this.remoteFlag = remoteFlag;
return this;
}

public Builder dataFlag(boolean dataFlag) {
this.dataFlag = dataFlag;
return this;
}

public Builder addTimeout(long timeout) {
this.timeout = timeout;
return this;
}

public ClientKey build() {
return new ClientKey(this);
}
}

public long getUserId() {
return userId;
}

public int getClientId() {
return clientId;
}

public long getTimeout() {
return timeout;
}

public Map<String, String> getParameterMap() {
return parameterMap;
}

public boolean isDataFlag() {
return dataFlag;
}
}

在我上面的 ClientKey 中,有时我会在创建 ClientKey 对象时传递 parameterMap,但有时它会是 null。我们并不总是会设置parameterMap。以下是我在我的应用程序代码中设置并传递 ClientKey 对象后在我的应用程序代码中迭代 parameterMap 的方式:

final Map<String, String> parameterMap = clientKey.getParameterMap();
if (!MapUtils.isEmpty(parameterMap)) {
Set<Entry<String, String>> params = parameterMap.entrySet();

for (Entry<String, String> e : params) {
url.append("&").append(e.getKey());
url.append("=").append(e.getValue());
}
}

问题是 - 我如何确保我的 parameterMap 在设置后不会在其间被修改。如您所见,一旦我构建了 ClientKey 对象,parameterMap 只会被读取而不会被修改。然而,它依赖于这样一个事实,即没有恶意或错误的客户端不会在此期间尝试修改,那么防止这种情况的最佳方法是什么?

最佳答案

如果您想防止在 ClientKey 之后对 map 内容 进行任何 修改|实例已经创建,你应该在构造函数中使用它:

    if (builder.parameterMap == null) {
this.parameterMap = null;
} else {
this.parameterMap = Collections.unmodifiableMap(builder.parameterMap);
}

如果你想允许来自 ClientKey 的修改只有代码,而不是来自外部,你应该返回一个 unmodifiableMap()getParameterMap()相反,但它不会是完全线程安全的 - 你必须使用 ConcurrentMap那么。

关于java - 如何确保我的 map 在我的构建器模式中设置后永远不会被修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30017694/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com