惡漢式java
package cn.foxeye.design.singleton; public class Singleton { private static Singleton instance = new Singleton(); public Singleton() { } public static Singleton getInstance() { return instance; } }
懶漢式this
package cn.foxeye.design.singleton; public class Singleton2 { private static Singleton2 instance = null; private Singleton2() { } public static synchronized Singleton2 getInstance() { if (instance == null) { instance = new Singleton2(); } return instance; } }
雙重檢查加鎖spa
package cn.foxeye.design.singleton; public class Singleton3 { private static Singleton3 instance = null; private Singleton3() { } public static Singleton3 getInstance() { if(instance == null) { synchronized (Singleton3.class) { if(instance == null) { instance = new Singleton3(); } } } return instance; } }
Lazy initialization holder class模式code
package cn.foxeye.design.singleton; public class Singleton4 { private Singleton4() { } private static class SingletonHolder { private static Singleton4 instance = new Singleton4(); } public static Singleton4 getInstance() { return SingletonHolder.instance; } }
枚舉式ci
package cn.foxeye.design.singleton; public enum Singleton5 { uniqueInstance; private String name; private String sex; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }