java设计模式-单例

101 阅读1分钟

主要是为了避免重复创建对象

大体有饿汉式、synchronized懒汉式、双重检查、静态内部类、枚举五种实现方式

饿汉式:

public class Test1 {
    private final static Test1 test1 = new Test1();
    private Test1(){

    }
    public static Test1 getInstance(){
        return test1;
    }
}

synchronized懒汉式:

public class Test2 {
    private static Test2 test2;
    private Test2(){

    }
    public synchronized static Test2 getInstance(){
        if(test2 == null){
            test2 = new Test2();
        }
        return test2;
    }
}

双重检查:

public class Test3 {
    private static volatile Test3 test3;
    private Test3(){

    }
    public static Test3 getInstance(){
        if(test3 == null){
            synchronized (Test3.class){
                if(test3 == null){
                    test3 = new Test3();
                }
            }
        }
        return test3;
    }
}

静态内部类:

public class Test4 {
    private Test4(){

    }
    private static class Holder{
        private static final Test4 test4 = new Test4();
    }
    public static Test4 getInstance(){
        return Holder.test4;
    }
}

枚举:

public enum  Test5 {
    INSTANCE;
}