您的位置:首页 > 其它

単例模式

2016-07-24 22:18 459 查看
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() {  

     }

    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: