标签:
恶汉式
package cn.foxeye.design.singleton;
public class Singleton {
private static Singleton instance = new Singleton();
public Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
懒汉式
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;
}
}
双重检查加锁
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模式
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;
}
}
枚举式
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;
}
}
标签:
原文地址:http://my.oschina.net/u/1995545/blog/363378