单例模式,我们平常写的有好几种,下面有其中的五种
/**
* 单例模式1,存在线程不安全问题,若不考虑线程安全可以用*
* @author tarena
*
*/
class Singleton1 {
private static Singleton1 singleton;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (singleton == null) {
singleton = new Singleton1();
}
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
* 单例模式2,线程安全了,但会因为线程同步,引起线程堵塞
* 若是不考虑大并发情况下,也可以用。
* @author tarena
*
*/
class Singleton2 {
private static Singleton2 singleton;
private Singleton2() {
}
public synchronized static Singleton2 getInstance() {
if (singleton == null) {
singleton = new Singleton2();
}
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
/**
*
* @author tarena
*
*/
class Singleton3 {
private static Singleton3 singleton;
private Singleton3() {
}
public static Singleton3 getInstance() {
if (singleton == null) {
synchronized (Singleton3.class) {
if (singleton == null) {
singleton = new Singleton3();
}
}
}
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
* 单例模式4,线程安全了,并发访问速度更快了,
* 缺点:假如对象比较大,类加载时就创建了此对象,假如不使用,就可能长时间占用内存。
* @author tarena
*
*/
class Singleton4 {//非大对象时用
private static final Singleton4 singleton=new Singleton4();
private Singleton4(){
}
public static Singleton4 getInstance() {
return singleton;
}
}
--------------------------------------------------------------------------------------------------------------------------------------
* 单例模式5,线程安全了,并发访问速度更快了
*
* @author tarena
*
*/
class Singleton5 {//大对象时,就用这种
private Singleton5(){
}
//什么时候需要什么时候构建实例。
static class Lazy{
private static final Singleton5 singleton=new Singleton5();
}
public static Singleton5 getInstance() {
return Lazy.singleton;
}
}
以上五种供参考学习,推荐用第五种。