设计模式之单例模式示例

  • 饿汉式
/**
 * 
 * @author lxw
 *
 *饿汉式 ,不使用时创建导致内存浪费,反射能够破坏
 *优点,使用时效率高,直接使用不用在创建线程安全
 */
public class PositiveSingleton {

    private static PositiveSingleton instance = new PositiveSingleton();
    
    private PositiveSingleton(){
        
    }
    
    public static PositiveSingleton getInstance(){
        return instance;
    }
}
  • 懒汉式
/**
 * 
 * @author lxw
 *优点:使用时创建,相对来说不会浪费内存空间
 *缺点:多线程情况下,不安全,反射能够破坏
 */
public class LazySingleton {

	private static LazySingleton instance;
	
	private LazySingleton(){
		
	}
	
	public static LazySingleton getInstace(){
		if (instance == null){
			instance = new LazySingleton();
		}
		return instance;
	}
}
/**
 * 
 * @author lxw
 *优点:线程安全,不造成内存浪费
 *缺点:多线程访问,导致方法阻塞线程,影响效率,反射能够破坏
 */
public class LazyThreadSingleton {

	private static LazyThreadSingleton instance;
	
	
	private LazyThreadSingleton(){}
	
	public synchronized static LazyThreadSingleton getInstance(){
		if (instance == null){
			instance = new LazyThreadSingleton();
		}
		return instance;
	}
}
/**
 * 
 * @author lxw
 *优点:线程安全
 *缺点:效率低,反射能够破坏
 */
public class LazyThreadSingletonFunction {

	private static LazyThreadSingletonFunction instance;
	
	private LazyThreadSingletonFunction(){}
	
	public static LazyThreadSingletonFunction getInstance(){
		synchronized (LazyThreadSingletonFunction.class) {
			if (instance == null){
				instance = new LazyThreadSingletonFunction();
			}
		}
		return instance;
	}
}
/**
 * 
 * @author lxw
 *
 *优点:线程安全,效率较高
 *缺点:不够优雅,反射能够破坏
 */
public class LazyThreadDubboSingleton {

	private static LazyThreadDubboSingleton instance;
	
	private LazyThreadDubboSingleton(){}
	
	public static LazyThreadDubboSingleton getInstance(){
		if (instance == null){
			synchronized (LazyThreadDubboSingleton.class) {
				if (instance == null){
					instance = new LazyThreadDubboSingleton();
				}
			}
		}
		
		return instance;
	}
}
/**
 * 
 * @author lxw
 * 优点:线程安全,不浪费内存空间
 * 缺点:不优雅, 反射能够破坏
 */
public class StaticInnerClass {

	
	private StaticInnerClass(){}
	
	public static StaticInnerClass getInstance(){
		return InnerLazy.instance;
	}
	
	private static class InnerLazy {
		public static StaticInnerClass instance = new StaticInnerClass();
	
	}
}
/**
 * 
 * @author lxw
 *优雅,官方推荐,反射不能破坏
 */
public enum EnumSingleton {
	INSTANCE;
	
	private Object data;
	
	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}

	public static EnumSingleton getInstance(){
		return INSTANCE;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值