1、第一种-->饱汉模式(支持并发)
package com.test;
/**
* @author Administrator
* @date 2018/6/9
*/
public class TestSingleTon {
private TestSingleTon(){
}
private static final TestSingleTon testSingleTon = new TestSingleTon();
/**
* 饱汉模式
* @return
*/
private static TestSingleTon getInstance(){
return testSingleTon;
}
}
2、第二种-->恶汉模式(不支持并发)
package com.test;
/**
* @author Administrator
* @date 2018/6/9
*/
public class TestSingleTonA {
private TestSingleTonA() {
}
private static TestSingleTonA testSingleTon;
/**
* 饿汉模式
* 不支持并发,在实例化的时候,有可能出现并发
* @return
*/
private static TestSingleTonA getInstance() {
if (testSingleTon == null) {
testSingleTon = new TestSingleTonA();
}
return testSingleTon;
}
}
3、第三种-->双重校验模式(支持并发)
package com.test;
/**
* @author Administrator
* @date 2018/6/9
*/
public class TestSingleTonB {
private TestSingleTonB() {
}
private volatile static TestSingleTonB testSingleTon;
/**
* 饿汉模式 支持并发
* 双重校验
* @return
*/
private static TestSingleTonB getInstance() {
if (testSingleTon == null) {
synchronized (TestSingleTonB.class) {
if (testSingleTon == null) {
testSingleTon = new TestSingleTonB();
}
}
}
return testSingleTon;
}
}