1:餓漢模式java
public class MyObject { // 當即加載方式 == 餓漢模式 private static MyObject myObject= new MyObject(); private MyObject(){} public static MyObject getInstance(){ return myObject; } }
2:懶漢模式code
public class MyObject { private static MyObject myObject; private MyObject(){} synchronized public static MyObject getInstance(){ if (myObject == null) { myObject = new MyObject(); } return myObject; } }
注意:加入同步synchronized關鍵字獲得相同實例的對象,但此種方式的運行效率很是低。對象
解決方法:使用DCL(Double-Check Locking)get
public class MyObject { private static MyObject myObject; private MyObject(){} public static MyObject getInstance(){ if (myObject == null) { synchronized (MyObject.class) { if (myObject == null) { myObject = new MyObject(); } } } return myObject; } }
3:靜態內置類同步
public class MyObject { private static class MyObjectHandler{ private static MyObject myObject = new MyObject(); } private MyObject() { } synchronized public static MyObject getInstance() { return MyObjectHandler.myObject; } }
4:序列化與反序列化的單例模式實現io
public class MyObjectSerializable implements Serializable { private static final long serialVersionUID = 888L; private static class MyObjectHandler{ private static final MyObjectSerializable myObject = new MyObjectSerializable(); } private MyObjectSerializable() { } protected Object readResolve() throws ObjectStreamException { return MyObjectHandler.myObject; } }
5:使用靜態代碼塊class
public class MyObject { private static MyObject myObject; static { myObject = new MyObject(); } private MyObject() { } synchronized public static MyObject getInstance() { return myObject; } }
6:使用enum枚舉數據類型效率