Java的设计模式的学习【一】 -- 单例模式

应用场合:有些对象只需要一个,比如:配置文件,工具类,线程池、缓存、日志对象等;

常用的有懒汉模式和饿汉模式两种单例模式;(构造方法:私有化,不允许外部直接创建)

区别:

【饿汉模式】- 类加载的时候就创建了类的实例,所以加载类时比较慢,但运行时获取对象的速度比较快;线程安全;

/**
 * 单例模式 -  饿汉模式
 * 类加载时就创建类的实例
 * @author chenj
 */
public class Singleton {
	
	private static Singleton instance = new Singleton();
	public static Singleton getInstance(){
		return instance;
	}
	
	public static void main(String args[]){
		Singleton st1 = Singleton.instance;
		Singleton st2 = Singleton.instance;
		if(st1 == st2){
			System.out.println("s1和s2是同一个实例");
		} else {
			System.out.println("s1和s2不是同一个实例");
		}
	}
}

【懒汉模式】- 类使用的时候才创建类的实例,所以加载类时比较快,但运行时获取对象的速度比较慢;线程不安全;

/**
 * 单例模式 - 懒汉模式
 * 类使用时才创建类的实例
 * @author chenj
 */
public class Singleton {
	
	private static Singleton instance;
	public static Singleton getInstance(){
		if(instance == null){
			instance = new Singleton();
		}
		return instance;
	}
	
	public static void main(String args[]){
		Singleton st1 = Singleton.instance;
		Singleton st2 = Singleton.instance;
		if(st1 == st2){
			System.out.println("s1和s2是同一个实例");
		} else {
			System.out.println("s1和s2不是同一个实例");
		}
	}
}

   

猜你喜欢

转载自chenjie1121.iteye.com/blog/2212831