Java单例模式

懒汉式

public class Singleton {

	private static Singleton singleton = null;

	// 构造方法私有化
	private Singleton() {
	}

	public static Singleton getInstance() {
		if (null == singleton) {
			synchronized (Singleton.class) {
				if (null == singleton) {
					singleton = new Singleton();
				}
			}
		}
		return singleton;
	}
}


 饿汉式

public class Singleton {

	// 构造方法私有化
	private Singleton() {
	}

	private static Singleton singleton = new Singleton();

	public static Singleton getInstance() {
		return singleton;
	}
}

 

使用内部类实现

public class Singleton{

	private Singleton(){
		
	}
	
	private static class innerClass {
		private static Singleton singleton = new Singleton();
	}
	
	public static Singleton getIntance(){
		return innerClass.singleton;
	}
}



 

你可能感兴趣的:(Java单例模式)