饿汉式懒汉式的调用方法,给个加注释的例子,写了亲

解决方案 »

  1.   

    http://www.iteye.com/topic/1121918
      

  2.   

    public class Singleton{
    private static Singleton{};
    private static Singleton st=new Singleton();
    public static Singleton get(){
    return st;
    }
      

  3.   

    懒汉式
    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;  
            }  
    }  
      

  4.   

    利用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;
    }
       }
    }
      

  5.   


    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;
        }}