首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

单例设计形式

2013-04-09 
单例设计模式饿汉式懒汉式的调用方法,给个加注释的例子,写了亲[解决办法]http://www.iteye.com/topic/1121

单例设计模式
饿汉式懒汉式的调用方法,给个加注释的例子,写了亲
[解决办法]
http://www.iteye.com/topic/1121918
[解决办法]
public class Singleton{
private static Singleton{};
private static Singleton st=new Singleton();
public static Singleton get(){
return st;
}
[解决办法]
懒汉式

public class LazySingleton {  
  
   private static LazySingleton instance = null;  
  
   private LazySingleton(){};  
  
   public static synchronized LazySingleton getInstance(){  
  
   if(instance==null){  
     instance = new LazySingleton();  
     }  
  
   return instance;  
  }  
}
  

饿汉式
public class EagerSingleton {  
  
         private static EagerSingleton instance = new EagerSingleton();  
  
         private EagerSingleton(){};  
  
         public static EagerSingleton getInstance(){  
            return instance;  
        }  
}
  
[解决办法]
这两种方式调用的时候是一样的,就只有初始化的时间不一样。

前一种是在定义这个对象的时候就初始化,也就是类加载的时候。
后一种是在调用这个方法的时候才初始化。

上面例子很清晰了。
[解决办法]
利用JAVA加载静态内部类的原理,实现懒汉加载,不需要同步
public class TestObject{
   private TestObject(){}

   public static TestObject instance(){
        return InnerSingletonHandler.getSingleton();
   }

   private static class InnerSingletonHandler{
        private static TestObject singleton = new TestObject();

private InnerSingletonHandler(){}

private static TestObject getSingleton(){
return singleton;
}
   }
}
[解决办法]

package com.javapatterns.singleton;

/**
 * 饿汉式单例类
 *
 */
public class EagerSingleton {
    
    private static final EagerSingleton m_instance = new EagerSingleton();
    
    /**
     * 私有的构造方法
     */
    private EagerSingleton(){
        
    }
    
    /**
    
     * 功能:静态工厂方法
     * @return EagerSingleton


     * @param @return
     * @date 2013-4-4
     * @author arch_mage
     */
    public static EagerSingleton getInstance() {
        return m_instance;
    }
    

}




package com.javapatterns.singleton;

/**
 * 懒汉式单例类
 *
 */
public class LazySingleton {
    
    private static LazySingleton m_instance = null;
    
    /**
     * 私有构造方法
     */
    private LazySingleton() {
         
    }
    
    synchronized public static LazySingleton getInstance() {
        if(m_instance == null) {
            m_instance = new LazySingleton();
        }
        return m_instance;
    }

}

热点排行