我们在属性文件中有一些数据.这些数据用于许多类.因此,我们在每个类中创建一个Properties类对象,然后使用getProperty()方法读取数据.这导致代码重复.
有人可以建议一些最佳做法来避免这种情况吗?
我想到的一件事是:
创建一个类
为此类的属性文件中的每个属性设置一个公共变量
有一个方法为每个属性分配值
在需要属性值的类中,为此创建一个对象类和访问公共变量
但是,我不喜欢这种方法的是公共变量,如果在属性文件中添加了新属性,我需要添加代码来读取类中的该属性.
任何帮助表示赞赏.
谢谢!
Cri*_*ses 20
您可以创建一个Singleton类,它在第一次调用时加载属性..以及一个检索给定属性键的属性值的公共方法.
这假设您正在使用标准属性文件...但您可以将其推断为任何键值对,将属性类型更改为Map或其他内容.
就像是
public class PropertyHandler{
private static PropertyHandler instance = null;
private Properties props = null;
private PropertyHandler(){
// Here you could read the file into props object
this.props = .....
}
public static synchronized PropertyHandler getInstance(){
if (instance == null)
instance = new PropertyHandler();
return instance;
}
public String getValue(String propKey){
return this.props.getProperty(propKey);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以根据需要调用它..从任何代码..像这样.
String myValue = PropertyHandler.getInstance().getValue(propKey);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
12295 次 |
| 最近记录: |