単例模式

来源:互联网 发布:住户部门贷款数据 编辑:程序博客网 时间:2024/04/29 07:18
public class SimpleTest {

    //    饿汉模式

    private SimpleTest(){

    }
    private static SimpleTest instance = new SimpleTest();

    public static SimpleTest getinstance(){

        return instance;
    }

}




public class SimpleTest1 {
//    懒汉模式    
        private SimpleTest1(){
            
        }
        private static SimpleTest1 instance;
        
        
        public static SimpleTest1 getInstance(){
            if(instance == null){
                instance = new SimpleTest1();
            }
            return instance;
        }
    }


//线程安全
    private volatile static  SimpleTest3 singleton;  

    private SimpleTest3(){

    }

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


public class SimpleTest4 {
//     静态内部类单例模式
    private SimpleTest4(){
    }
    
    public static SimpleTest4 getInstance(){  
        return SingletonHolder.sInstance;  
    }
    
    private static class SingletonHolder {  
        private static final SimpleTest4 sInstance = new SimpleTest4();  
    }  
    
}


//枚举单例的优点就是简单,但是大部分应用开发很少用枚举,可读性并不是很高,不建议用。
public enum SimpleTest5 {
    
     INSTANCE;  
     public void doSomeThing() {  
     }
    
}


1 0
原创粉丝点击