简单的实现一个单例
设计模式
使用单例模式读取properties文件
(1)先创建一个properties文件
(2)创建单利模式(饿汉式)
package singleton;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class AppConfig {
private static AppConfig instance = new AppConfig();
private String paramA;
private String paramB;
private AppConfig() {
readConfig();
}
public static AppConfig getInstance(){
return instance;
}
public String getParamA() {
return paramA;
}
public String getParamB() {
return paramB;
}
/**
* 读取properties文件
*/
private void readConfig(){
Properties properties = new Properties();
InputStream in = null;
try {
in = AppConfig.class.getResourceAsStream("/config.properties");
properties.load(in);
//把配置文件的内容读出来设置到属性上
this.paramA = properties.getProperty("paramA");
this.paramB = properties.getProperty("paramB");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
(3)编写客户端代码
package singleton;
public class Client {
public static void main(String[] args) {
AppConfig config = AppConfig.getInstance();
String paramA = config.getParamA();
String paramB = config.getParamB();
System.out.println("paramA="+paramA+" paramB="+paramB);
}
}
(4)运行结果