单例模式

核心作用:
---保证一个类只有一个实例,并且提供一个访问该实例的全局访问点。
1.饿汉式
优点:线程安全;调用效率高;
缺点:不能延时加载
例子:
/**
* .饿汉式
*/
public class Testa {
private static Testa testa=new Testa();//类加载时立即加载这个对象
private Testa(){
};
public static Testa getTesta(){
return testa;
}
2.懒汉式
优点:线程安全; 能延时加载;
缺点:调用效率低;
例子:

/**
* 懒汉式
*/
public class Testa {
private static Testa testa;//类加载时立即加载这个对象
private Testa(){
};
/**
* synchronized 同步块
* 防止new多个对象
*/
public static synchronized Testa getTesta(){
if(testa==null){
testa =new Testa();
}
return testa;
}
3.静态内部类实现方法

例子:
public class Testa {
private static class text{
private static final Testa testa=new Testa();
}
private Testa(){
};

public static synchronized Testa getTesta(){

return text.testa;
}


4.枚举方式

posted @ 2018-03-04 19:07  ●ら任┊逍遥  阅读(66)  评论(0编辑  收藏  举报