设计模式之单例模式

                                               单例模式

饿汉式

public class HungrySingleTon {
    private static HungrySingleTon instance = new HungrySingleTon();

    public static HungrySingleTon getInstance() {
        return instance;
    }
    
    private HungrySingleTon() {
        
    }
}

 懒汉式

public class LazySingleTon {
    private static LazySingleTon instance = null;

    public static LazySingleTon getInstance() {
        if(instance == null) {
            instance = new LazySingleTon();
        }
        return instance;
    }

    private LazySingleTon() {

    }
}

 

多线程下的单例模式

public class SyncSingleTon {
    private static SyncSingleTon instance = null;

    public static SyncSingleTon getInstance() {
        if(instance == null) {
            synchronized (SyncSingleTon.class) {
                if(instance == null) {
                    instance = new SyncSingleTon();
                }
            }
        }
        return instance;
    }
    
    private SyncSingleTon() {
        
    }
}

解决Java指令重排的问题

public class VolatileSingleTon {
    private static volatile VolatileSingleTon instance = null;
    
    public static VolatileSingleTon getInstance() {
        if(instance == null) {
            synchronized(VolatileSingleTon.class) {
                if(instance == null) {
                    instance = new VolatileSingleTon();
                }
            }
        }
        return instance;
    }
    
    private VolatileSingleTon() {
        
    }
}

 

 

 

 

你可能感兴趣的:(Java,volatile,singleton)