Java 五中簡單的創建單例方法
1.線程不安全
public class SingleTest {
? ? ? ? private static SingleTest single = null;
? ? ? ? public static?SingleTest? getSingleTest(){
? ? ? ? ? ? ? ? if(single == null){
? ? ? ? ? ? ? ? ? ? single = new SingleTest();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? return single;
????????}
}
2.同步鎖
public class SingleTest {
? ? ? ? private static SingleTest single = null;
? ? ? ? public static synchronized SingleTest? getSingleTest(){
? ? ? ? ? ? ? ? if(single == null){
? ? ? ? ? ? ? ? ? ? single = new SingleTest();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? return single;
????????}
}
3.減少鎖的范圍
public class SingleTest {
? ? ? ? private static SingleTest single = null;
????????public static SingleTest? getSingleTest(){
? ? ? ? ? ? ? ? if(single == null){
? ? ? ? ? ? ? ? ? synchronized(this){
? ? ? ? ? ? ? ? ? ? ? ? if(single? == null){
????????????????????????????single = new SingleTest();
? ? ? ? ? ? ? ? ? ? ? ? ?}
????????????????????}
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? return single;
????????}
}
4.靜態初始化
public class SingleTest {
? ? ? ? private static SingleTest single = null;?
? ? ? ? static {
? ? ? ? ? ? single = new SingleTest();
????????}
? ? ? ? public static?SingleTest? getSingleTest(){
? ? ? ? ? ? ? ? return single;
????????}
}
5.靜態內部類
public class SingleTest {
? ? ? ? private static class SingleHolder {
? ? ? ? ? ? ? private static SingleTest single?= new?SingleTest ();
????????}
? ? ? ? public static?SingleTest? getSingleTest(){
? ? ? ? ? ? return?SingleHolder.single ;
????????}
}