最近,在一个系统中用到配置,设计了一个基类,继承了Thread,以监视配置文件的变化:
package cs.Config;
public abstract class BaseConfig extends Thread {
private String url;
private int ldLastModified = 0L;
private static int ISINVALID_SCAN_TIME = 10;
protected BaseConfig(String url) throws Exception {
setUrl(url);
String XMLconfig = loadConfigFile();
this.oldLastModified = XMLconfig.hashCode();
setXmlConfig(XMLconfig);
setDaemon(true);
start();
}
public void run() {
while (true) {
long time = 1000L;
time *= ISINVALID_SCAN_TIME;
try {
String XMLconfig = loadConfigFile();
int nowlastModified = XMLconfig.hashCode();
if (nowlastModified != this.oldLastModified) {
this.oldLastModified = nowlastModified;
setXmlConfig(XMLconfig);
System.out.println("configXML Loading new");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
Thread.sleep(time);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public abstract void setXmlConfig(String ConfigString)
throws BusinessException;
}
再设计一个具体类:
package cs.Config;
public class SystemConfig extends BaseConfig {
private SystemXmlConfig configXML;
private String url = "";
public SystemConfig(String url) throws BusinessException {
super(url);
this.url = url;
}
public void setXmlConfig(String ConfigString) throws BusinessException {
this.configXML = new SystemXmlConfig(ConfigString);
if (this.configXML == null)
throw new Exception("不能创建SystemXmlConfig对象:" + ConfigString);
}
public SystemXmlConfig getXmlConfig() throws BusinessException {
if (this.configXML == null)
new SystemConfig(this.url);
return this.configXML;
}
}
原来SystemConfig类的getXmlConfig是Static方法,configXML也是Static成员,有初始化=null,因采用静态方法和成员,系统只能用到一个配置文件,想能用到多个配置文件,所以改成了实例方法和成员。
本例中有一点比较特殊,就是在父类的构造中用到了子类的方法setXmlConfig,此时,子类的configXML 变量还未初始化,如果在子类中有初始化动作,则子类的初始化动作在父类的构造执行后再执行,则造成原来的值丢失。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/81227/viewspace-694865/
,如需转载,请注明出处,否则将追究法律责任。