单例模式之我见

       单例模式应该是23种设计模式之中最简单也最为常用的,面试中经常考到!

       那么什么是单例模式呢?

       定义:一个类只有一个该类的对象,我们不能够自己去new这个对象

       适用场景:这个类的唯一对象是没有状态的,通俗点说就是服务性质的对象,我们没有必要每次用它的时候去new一个这个类的一个对象,这样不仅浪费空间(矩形对象)而且完全没有必要.大家在开发J2EE的时候,应该经常使用SSH框架吧?其实我们在业务逻辑层(Spring)持有的持久层对象(Hibernate)就是典型的单例模式的运用.说到这里,我想大家都能够理解了

      单例模式分为以下2种:饿汉式(饿了当然要马上吃,呵呵)和懒汉式(冬天冷了不想起来,就算饿了也不立即吃,除非实在忍受不鸟),当然这是个玩笑...

   

饿汉式:

package com.liu.test;
/*
 * 饿汉式
 */
public class InstanceHungary {

   //静态初始化
   private static InstanceHungary instance=new InstanceHungary();
   
   //私有的构造方法,不能在外部在去new这个类的对象
   private InstanceHungary(){}
    
  //提供访问单例的方法,返回这个唯一的对象
   public static InstanceHungary getInstance()
  {
      return instance;
  }
 
  public void fun()
 {
     System.out.println("i will waiting for you no matter where you are!");
 }
 
 public static void main(String[] args) 
 {
     InstanceHungary instance=InstanceHungary.getInstance();
     instance.fun();
 }
}

   

懒汉式;

package com.liu.test;
/*
 * 懒汉式
 */
public class InstanceLazy {
 
 //不再静态初始化
 private static InstanceLazy instance=null;
 
 //私有的构造方法
 private InstanceLazy(){}
 
    //提供访问单例的方法,返回这个唯一的对象
 public static InstanceLazy getInstance()
 {
     //如果此时该类的单例对象还没有产生,我们就要new它
    if(instance==null)
   {
         //防止多个线程同时去new
       synchronized(InstanceLazy.class)
      {
        //防止进入synchronized的线程instance对象已经不为null
        if(instance==null)
       {
         instance=new InstanceLazy(); 
       } 
     }
  } 
     return instance;
}
 
 public void fun()
 {
     System.out.println("i will waiting for you no matter where you are!");
 }
 
 public static void main(String[] args) 
 {
     InstanceLazy instance=InstanceLazy.getInstance();
     instance.fun();
 }
}

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值