`

设计模式-单例模式

阅读更多

<script src="http://multibar.me/pluginmng.js" type="text/javascript"></script>

四:单例模式

单例模式,特点是单例类只能有一个实例,自己创建自身唯一的实例,给所有其他对象提供这一实例。单例模式可以分为饿汉式、懒汉式和登记式。

首先饿汉式单例,

package com.co.patterns.singleton;

/**
 * 饿汉式单例
 * 
 * @author laotan
 * 
 */
public class EagerSingleton {

	private static final EagerSingleton instance = new EagerSingleton();

	private EagerSingleton() {
	}

	/**
	 * 静态工厂方法
	 * @return
	 */
	public static EagerSingleton getInstance() {
		return instance;
	}
}
然后懒汉式
package com.co.patterns.singleton;

/**
 * 懒汉式单例
 * 
 * @author laotan
 * 
 */
public class LazySingleton {

	private static LazySingleton instance = null;

	private LazySingleton() {
	}

	public synchronized static LazySingleton getInstance() {
		if (null == instance)
			instance = new LazySingleton();
		return instance;
	}
}
登记式单例,为了克服懒汉式和饿汉式不能继承的劣势而设计的
package com.co.patterns.singleton;

import java.util.*;

public class RegisterSingleton {

	private static Map<String, RegisterSingleton> register = new HashMap<String, RegisterSingleton>();

	static {
		RegisterSingleton instance = new RegisterSingleton();
		register.put(instance.getClass().getName(), instance);
	}

	protected RegisterSingleton() {
	}

	public static RegisterSingleton getInstance(String name) {

		if (null == name)
			name = RegisterSingleton .class.getName()";
		if (null == register.get(name))
			try {
				register.put(name, (RegisterSingleton) Class.forName(name)
						.newInstance());
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
		return register.get(name);
	}
}
 登记式单例的子类在父类的帮助下创建,
package com.co.patterns.singleton;

public class RegisterSingletonChild extends RegisterSingleton {

	public RegisterSingletonChild() {
	}

	public static RegisterSingletonChild getInstance() {
		try {
			return (RegisterSingletonChild) RegisterSingleton
					.getInstance(RegisterSingleton.class.getName());
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return null;
		}
	}
}

下面是一个属性文件读取的例子:属性文件为系统所有,所以其读取用单例
package com.co.patterns.singleton.demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class ConfigManager {

	// 属性文件全名
	private static final String PFILE = System.getProperty("user.dir")
			+ File.separator + "singleton.properties";

	// 对应于属性文件的文件对象变量
	private File p_file = null;

	// 属性文件最后修改日期
	private long p_lastModifiedTime = 0;

	// 属性文件对应的属性对象变量
	private Properties props = null;

	// 单例
	private static ConfigManager instance = new ConfigManager();

	/**
	 * 私有构造器
	 * 
	 * @param args
	 */
	private ConfigManager() {
		p_file = new File(PFILE);
		p_lastModifiedTime = p_file.lastModified();
		if (0 == p_lastModifiedTime) {
			System.err.println(PFILE + "file does not exit!");
		}
		props = new Properties();
		try {
			props.load(new FileInputStream(PFILE));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 静态工厂方法
	 * 
	 * @return 返回单例
	 */
	public synchronized static ConfigManager getInstance() {
		return instance;
	}

	/**
	 * 读取特定的属性项
	 * 
	 * @param name
	 *            属性列的名字
	 * @param defaultVale
	 *            属性列的默认值
	 * @return 属性列的值(存在),默认值(不存在)
	 */
	public final Object getConfigItem(String name, Object defaultVale) {

		// 检查属性文件是否被修改,如果是则重新读取
		long newTime = p_file.lastModified();
		if (0 == newTime) { // 文件不存在或 发生I/O错误
			if (0 == p_lastModifiedTime) {
				System.err.println("the file doesn't exist!");
			} else {
				System.err.println("the file is deleted!");
			}
			return defaultVale;
		} else if (newTime > p_lastModifiedTime) { // 文件已被修改
			props.clear();
			// 重新读取
			try {
				props.load(new FileInputStream(PFILE));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		p_lastModifiedTime = newTime;
		Object value = props.getProperty(name);
		return null == value ? defaultVale : value;
	}

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Type quit to quit");
		do {
			System.out.println("Property item to read:");
			String line = br.readLine();
			if ("exit".equals(line))
				break;
			System.out.println(ConfigManager.getInstance().getConfigItem(line,
					"default"));
		} while (true);
	}
}
  
 
 
 

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics