gpt4 book ai didi

java - 在构造函数中使用静态变量有意义吗?

转载 作者:行者123 更新时间:2023-12-01 16:47:56 25 4
gpt4 key购买 nike

在以下代码中,构造 PropertyValue 时,会填充两个静态集。这种方式有意义吗?

class PropertyValue{

String cid;
String property;
String value;

public static Set<String> properties = new HashSet<>();
public static Set<String> values = new HashSet<>();

public PropertyValue(String cid, String property, String value) {
this.cid = cid;
this.property = property;
this.value = value;

properties.add(property);
values.add(value);
}
}

最佳答案

看起来是一种键值对缓存设计,但非线程安全。

为什么用两组代替 map ?

您可以使用单例持有者和哈希表创建线程安全的单例

https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom

import java.util.Hashtable;
import java.util.Map;

public class Properties
{
private Map<String,String> properties = new Hashtable<>();

private Properties(){}

private static class PropertiesHolder{
private final static Properties instance = new Properties();
}

public static Properties getInstance(){
return PropertiesHolder.instance;
}

public void put(String property, String value){
properties.put(property, value);
}

public void get(String property){
properties.get(property);
}
}

并使用

    Properties properties = Properties.getInstance();
properties.put("foo","bar");
properties.get("foo");

和你的类(class)

class PropertyValue{

String cid;
String property;
String value;

public PropertyValue(String cid, String property, String value) {
this.cid = cid;
this.property = property;
this.value = value;

Properties properties = Properties.getInstance();
properties.put(property, value);
}
}

但我认为维护这个键值“存储”并不是PropertyValue类的责任该存储应该在新的 PropertyValue 实例之后(或之前)填充,但不能在构造函数中填充。

https://en.wikipedia.org/wiki/Single_responsibility_principle

如果不需要成对存储属性和值,可以保留两组字符串,或者直接在单例中存储一组 PropertyValue

关于java - 在构造函数中使用静态变量有意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46305960/

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