- 论坛徽章:
- 0
|
㊣ 定义
Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
㊣ 实现方式1
public class Singleton {
private static Singleton singleton = null;
private Singleton() {
}
synchronized public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public void doSomething() {
// ...
}
}
㊣ 实现方式2
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {
}
synchronized public static Singleton getInstance() {
return singleton;
}
public void doSomething() {
// ...
}
}
㊣ 测试
public class TestMain {
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.doSomething();
}
}
㊣ 实例演示
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
/**
* Singleton应用实例 -- 属性管理器
* 属性文件(*.properties)存放着系统的配置信息
* 属性是系统的一种资源,应当避免有多于一个的对象读取,特别是存储属性。
* @author peitian.lin@gmail.com
* @date 2006-08-22
*/
public class ConfigManager {
private static ConfigManager manager = new ConfigManager();
private final String FILE = "Singleton.properties";
private File file = null;
private long lastModifiedTime = 0;
private Properties properties = null;
private ConfigManager() {
file = new File(FILE);
lastModifiedTime = file.lastModified();
// File not exist
if (lastModifiedTime == 0) {
System.out.println("File not exist");
System.exit(-1);
}
// File exist
properties = new Properties();
try {
properties.load(new FileInputStream(file));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
synchronized public static ConfigManager getInstance() {
return manager;
}
final public String getConfigItem(String name, String defaultVal) {
// 检查文件是否被程序修改
long newTime = file.lastModified();
if (newTime == 0) {
if (lastModifiedTime == 0) {
// 属性文件不存在
System.out.println(FILE + " file does not exist!!");
System.exit(-1);
} else {
// 属性文件被删除
System.out.println(FILE + " file was deleted!!");
System.exit(-1);
}
} else if (newTime > lastModifiedTime) {
// 重新加载属性文件
properties.clear();
try {
properties.load(new FileInputStream(FILE));
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
lastModifiedTime = newTime;
String val = properties.getProperty(name);
if (val == null) {
val = defaultVal;
}
return val;
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/22660/showart_158374.html |
|