Java设计模式-单例 just for test

Singleton模式
问题:
    我有5个漂亮的老婆,她们的老公都是我,我就是Singleton,只要她们中的一个叫老公,就是我啦
(白日做梦一下下),怎样在建立"老公"的对象时保证一定是我呢?如何让一个类只创建一个实例。
解决:
    我们通过新建一个private static变量来记录这个唯一的实例,通过一个public static instance接口来获得唯一的实例。
代码:
//1.单例模式懒汉式
public class SingletonLazy {

private static SingletonLazy instance=null;

private SingletonLazy(){
  System.out.println("单例创建");
}
//synchronized 保证if(instance==null)判断的准确性
public synchronized static SingletonLazy getInstance()
{
  if(instance==null)
  {
   instance =new SingletonLazy();
  }
  return instance;
}
public static void main(String[] args)
{
  SingletonLazy s=SingletonLazy.getInstance();
  SingletonLazy p=SingletonLazy.getInstance();
}
}
//调试发现s,p的引用均是同一个对象,构造函数只调用了一次

//2.单例模式饿汉式
public class SingletonHungry {
private static SingletonHungry s=new SingletonHungry();
private SingletonHungry(){
  System.out.println("SingletonHungry 建立");
}
public static SingletonHungry getInstance()
{
  return s;
}
public static void main(String[] args)
{
  SingletonHungry s1=SingletonHungry.getInstance();
  SingletonHungry s2=SingletonHungry.getInstance();
}
}
总结:单例模式是gof23最简单的模式,但它的使用频率很高,应当掌握
           最后,饿汉式比懒汉式效率更高
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值