//单例模式设计
//恶汉式
class Test
{
private final Static Test test=new Test();
private Test(){}
public static Test getInstence(){
return test;
}
}
//懒汉式
class Test
{
private static Test test=null;
private Test(){}
public static Test getInstence(){
if(test==null){
synchronized (Test.class){
if(test=null){
test=new Test();
}
}
}
return test;
}
}
//懒汉式和饿汉式的区别:懒汉式延迟加载,但懒汉式在多线程并行访问时会出现安全问题,
//解决方法是使用同步函数,但是效率低一点(因为每个线程都要访问锁进行判断),解决方法是双重否定.
设计模式 之 单例模式
最新推荐文章于 2024-01-07 15:05:32 发布