单例模式: 在jvm中只存在一个实例。
//饿汉式: 天生就是线程安全的, 在类加载时就创建。
class TestSinleton{
static private TestSinleton testSingleton = new TestSinleton(); //静态的,在类加载时初始化创建
private TestSinleton(){} //私有构造, 防止在外面创建对象
static public TestSinleton getTestSinleton(){
return testSingleton ;
}
}
//懒汉式: 线程不安全, 在需要时创建
class TestSinleton{
static private TestSinleton testSingleton ;
private TestSinleton(){} //私有构造, 防止在外面创建对象
static public TestSinleton getTestSinleton(){//双重检查锁
if(null == testSingleton ){
synchronized(TestSinleton.class){
if(null == testSingleton){
testSingleton = new TestSinleton();
}
}
}
return testSingleton;
}
}