Java学习之单例模式

一、饿汉模式

public class MyObject {
	private static MyObject mObject = new MyObject();
	private MyObject(){}
	public static MyObject getInstance(){
		return mObject;
	}
}
二、懒汉模式

public class MyObjectOne {
	private MyObjectOne mObject = null;
	private MyObjectOne(){}
	public static MyObjectOne getInstance(){
		if(mObject == null){
			mObject = new MyObjectOne();
		}
		return mObject;
	}
}

只适合单线程情况,多线程下不能实现单例模式。

可以给getInstance()方法加上synchronized关键字,不过很影响程序运行的效率。

三、双重检测锁机制

public class MyObjectOne {
	private MyObjectOne mObject = null;
	private MyObjectOne(){}
	public static MyObjectOne getInstance(){
		if(mObject == null){
			synchronized (MyObjectOne.class) {
				if(mObject == null){
					mObject = new MyObjectOne();
				}
			}
		}
		return mObject;
	}
}

四、静态内置类实现单例模式

public class MyObjectTwo {
	private MyObjectTwo(){}
	public static MyObjectTwo getInstance(){
		return MyObjectHandler.mObject;
	}
	private static class MyObjectHandler{
		private static MyObjectTwo mObject = new MyObjectTwo();
	}
}

五、使用静态代码块实现单例模式

public class MyObjectTwo {
	private static MyObjectTwo mObject = null;
	static{
		mObject = new MyObjectTwo();
	}
	private MyObjectTwo(){}
	public static MyObjectTwo getInstance(){
		return mObject;
	}
}


你可能感兴趣的:(Java读书笔记,JAVA)