一、饿汉式O(线程安全):class MyObject{
private static MyObject object=new MyObject();
public static MyObject getobject(){
return object;
}
}
二、懒汉式(线程不安全)class MyObject{
private static MyObject object;
public static MyObject getobject(){
if(object==null)
{
object=new MyObject();
}
return object;
}
}
三、双重DCL(线程安全)class MyObject{
private static Voliate MyObject object;
public static MyObject getobject(){
if(object==null)
synchronized(MyObject.class)
{
if(object==null)
object=new MyObject();
}
return object;
}
}
四、懒汉式(线程安全,粗粒度)class MyObject{
private static MyObject object;
public synchronized static MyObject getobject(){
if(object==null)
{
if(object==null)
object=new MyObject();
}
return object;
}
}
五、静态内部类(线程安全)class MyObject{
public static class MyObjectHandler{
public static MyObject object=new MyObject();
}
public static MyObjcet getobject(){
return MyObjectHandler.object;
}
}
六、静态代码块(线程安全)class MyObject{
public static MyObject object;
static{
object=new MyObject();
}
public static MyObjcet getobject(){
return object;
}
}
七、枚举(线程安全)class MyObject{
}
public enum MyObjectHandler{
a;
public static MyObject object;
MyObjectHandle(){
object=new MyObject();
}
public static MyObject getobject(){
return object;
}
}