ckeditor貼上word圖片且圖片自動上傳控制元件
阿新 • • 發佈:2021-11-29
單例:一個類只有一個例項。
實現方式:1.私有化類的物件 2.類的建構函式私有化 3.提供一個公共的方法獲取類的物件
demo1:懶漢模式 (實現了lazy 載入 沒有加鎖 執行緒不安全)
public class Singleton01 { private static Singleton01 instance; private Singleton01() { } public static Singleton01 getInstance() { if (instance == null) { instance = newSingleton01(); } return instance; } }
demo2:餓漢模式(沒有lazy載入 消耗記憶體)
public class Singleton02 { private static Singleton02 instance = new Singleton02(); private Singleton02() { } public static Singleton02 getInstance() { return instance; } }
demo3: 懶漢模式加鎖(每次呼叫執行synchronized 效率低)
public class Singleton03 { private static Singleton03 instance; private Singleton03() { } public static synchronized Singleton03 getInstance() { if (instance == null) { instance = new Singleton03(); } return instance; } }
demo4: 雙檢鎖實現
public classSingleton04 { private static Singleton04 instance; private Singleton04() { } private static Singleton04 getInstance() { if (instance == null) { synchronized (Singleton04.class) { if (instance == null) { instance = new Singleton04(); } } } return instance; } }
demo5:靜態內部類實現 靜態內部類在呼叫的時候才初始化,靜態屬性只初始化一次
public class Singleton05 { private static class SingletonHolder { private static final Singleton05 INSTANCE = new Singleton05(); } private Singleton05() { } public static Singleton05 getInstance() { return SingletonHolder.INSTANCE; } }
demo6: emun列舉實現
public enum Singleton06 { INSTANCE; }
單例模式可以破壞嗎? 可以
方式一:通過反射破壞單例類
public class ReflectSingleton { public static void main(String[] args) throws Exception { Class clazz = Class.forName("com.wl.demo.demos.singleton.Singleton01"); Constructor constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); Singleton01 s1 = (Singleton01) constructor.newInstance(); Singleton01 s2 = (Singleton01) constructor.newInstance(); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); System.out.println(s1.equals(s2)); } }
解決辦法:建構函式丟擲異常:
private Singleton01() { if (instance != null) { throw new RuntimeException(); } }
方式二:序列化破壞單例
public class BreakSingleton { public static void main(String[] args) throws IOException, ClassNotFoundException { Singleton01 s1 = Singleton01.getInstance(); Singleton01 s2 = Singleton01.getInstance(); System.out.println(s1 == s2); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\file\\test.txt")); oos.writeObject(s1); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\file\\test.txt")); Singleton01 s3 = (Singleton01) ois.readObject(); System.out.println(s1.hashCode()); System.out.println(s2.hashCode()); System.out.println(s3.hashCode()); System.out.println(s1 == s3); } }
解決辦法:
//反序列化定義該方法,則不需要建立新物件 private Object readResolve() throws ObjectStreamException { return instance; }