单例模式之小弟我见

单例模式之我见

       单例模式应该是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();
 }
}

  

1 楼 tg008007x3 2010-12-21  
单例模式之小弟我见 很黄很暴力!
2 楼 爱在爪哇 2012-05-25  
还跟老子扯框架??源代码都没读的B还有资格扯?单例模式之小弟我见