单例模式的实现

饿汉式:

public class A {
private static A a = new A();
private A() {
}
public static A getInstance() {
return a;
}
}

懒汉式:(线程不安全)

public class A {
private static A a = null;
private A() {
}
public static A getInstance() {
If a == null {
A = new A();
}
return a;
}
}

懒汉式:(线程安全方式但不推荐)

public class A {
private static A a = null;
private A() {
}
public static synchronized A getInstance() {
If a == null {
A = new A();
}
return a;
}
}

懒汉式:(线程安全方式但有几率出错,因为对象的内存申请和初始化不同步的原因)

public class A {
private static A a = null;
private A() {
}
public static synchronized A getInstance() {
synchronized (A.class){
If a == null {
A = new A();
}
}
return a;
}
}

静态内部类方式:(推荐)

public class A {    
    private static class AHolder {    
        private static A a = new A();    
    }    
    private A (){}    
    public static A getInstance() { 
        return AHolder.a;   
    }    
}  

你可能感兴趣的:(单例模式的实现)