单例模式的五种写法
程序员文章站
2022-07-13 23:42:34
...
下面给出单例模式的五种写法:
package java面试宝典;
public class Singleton1 {
/*
* 推荐
*/
private static final Singleton1 instance=new Singleton1();
public static Singleton1 getInstance(){
return instance;
}
}
package java面试宝典;
public class Singleton2 {
/*
* 也不错
*/
private static class lazy{
public static final Singleton2 instance=new Singleton2();
}
public static Singleton2 getInstance(){
return lazy.instance;
}
}
package java面试宝典;
public class Singleton3 {
/*
* 线程安全,但是锁是重量级锁,效率低
*/
private static Singleton3 instance=null;
public static synchronized Singleton3 getInstance(){
if(instance==null){
instance=new Singleton3();
}
return instance;
}
}
package java面试宝典;
public class Singleton4 {
/*
* 双重判断加锁,效率比第三个更高,
*/
private static Singleton4 instance=null;
public static Singleton4 getInstance(){
if(instance==null){
synchronized(Singleton4.class){
if(instance==null){
instance=new Singleton4();
}
}
}
return instance;
}
}
package java面试宝典;
public class Singleton5 {
/*
* 非线程安全,不好
*/
private static Singleton5 instance=null;
public static Singleton5 getInstance(){
if(instance==null){
instance=new Singleton5();
}
return instance;
}
}
上一篇: Python初探
下一篇: Velocity语法