**1.**singleton单例模式:持有经常访问对象的一个实例,不用每次访问时都重新加载到内存中,不仅方便了对实例个数的控制,还节约了内存资源。
import java.util.Properties;
import java.io.IOException;
public class PropertyManager {
//JDK提供的类Properties,意为属性,特性
//静态成员和方法,每次编译的时候会执行
static Properties props = new Properties();
static {
try {
//配置文件的位置"config(包名)/xxx.properties(文件名)"
props.load(PropertyManager.class.getClassLoader().getResourceAsStream("config/xxx.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
}
配置文件xxx.properties内容的格式
如:count=13 等号左右均无空格
2. 从配置文件中读取信息来加载类,并new出新的对象
Test主程序中
Properties props = new Properties();
props.load(Test.class.getClassLoader().getResourceAsStream("com/chouwu/factory/vehicle.properties"));
String vehicle = props.getProperty("vehicle");
Object o = Class.forName(vehicle).newInstance();
Moveable m = (Moveable)o;
m.run();
配置文件中(等号左右均无空格)
vehicle=com.chouwu.factory.Car
Class.forName(xxx);将这个xxx字符串所代表的那个类load到内存,只是把class文件装载到内存中,并未产生新的对象,产生新的对象再加上newInstance(),也即Class.forName(xxx).newInstance();会调用它参数为空的构造方法,不过产生出来的对象是Object类型的,需要强制转换一下,在上述程序中Car这个类实现了Moveable接口

9708

被折叠的 条评论
为什么被折叠?



