一、饿汉模式
/**
*
*/
package com.me.singleton;
/**
* 单例设计模式:饿汉模式
* 不会出现线程安全问题,因为创建实例是用静态常量,只执行一次。
*/
public class EHanMode {
//用final修饰更加严谨性,一旦赋值就不能再改变。
private static final EHanMode em = new EHanMode();
private EHanMode() {
}
public static EHanMode getInstance() {
return em;
}
}
二、懒汉模式
/**
*
*/
package com.me.singleton;
/**
*
* 单例设计模式:懒汉模式,延迟加载对象。
*/
public class LanHanMode2 {
//不能用final修饰,否则一直为null。饿汉模式可以用final 修饰。
private static LanHanMode2 single = null;
private LanHanMode2() {
}
/**
* 此设计会产生多线程安全问题:当多个线程同时并发访问时会创建多个对象。
* @return
*/
/*
public static SingletonMode getInstance() {
if(null == single) {
single = new SingletonMode();
}
return single;
}
*/
/**
* 同步方法:
* 该设计模式解决了多线程安全问题,但是会造成性能下降,
* 当多个线程同时调用该方法时会处于堵塞等待状态,
* 只有当前一个线程调用执行完该方法后下一个线程才可以调用该方法。
* @return
*/
/*
public static synchronized SingletonMode getInstance() {
if(null == single) {
single = new SingletonMode();
}
return single;
}
*/
/**
* 同步代码块:此设计模式不仅叫解决线程安全问题,
* 还提高了性能,不用每次都创建同步监视器开销。
* @return
*/
public static LanHanMode2 getInstance() {
if(null == single) {
synchronized(LanHanMode2.class) {
if(null == single) {
single = new LanHanMode2();
}
}
}
return single;
}
}
/**
*
*/
package com.me.singleton;
/**
* 懒汉模式:线程安全,但性能低
*/
public class LanHanMode_Security {
private static LanHanMode_Security lms = null;
private LanHanMode_Security() {
}
/**
* 该设计解决了线程安全问题,
* 但是每次线程访问该方法时都要判断同步锁是否被占用,
* 加大了内存开销,效率低 。
* @return
*/
public static synchronized LanHanMode_Security getInstance() {
if(null == lms) {
lms = new LanHanMode_Security();
}
return lms;
}
}
/**
*
*/
package com.me.singleton;
/**
*
* 懒汉模式:线程安全,效率稍高
*/
public class LanHanMode_Security_Effective {
private static LanHanMode_Security_Effective lmse = null;
private LanHanMode_Security_Effective() {
}
public static LanHanMode_Security_Effective getInstance() {
if(null == lmse) {
synchronized(LanHanMode_Security_Effective.class) {
if(null == lmse) {
lmse = new LanHanMode_Security_Effective();
}
}
}
return lmse;
}
}