Java-Singleton(单例创建-饿汉式,懒汉式)

package com.easygo.singleton;
/**
 * Java单例有两种方式,饿汉式和懒汉式,饿汉式是在对象创建之前加载,优先于对象,而懒汉式是在对象创建完成后调用对象的方法来创建对象
 * ,了解JVM加载原理的都清楚,正真意义上的单例是饿汉式,在对象创建之前加载。
 * @author lx
 *
 */
public class Singleton {
//饿汉式
    public static Singleton singleton=null;
    static {
        singleton=new Singleton();
        
    }
    
    //懒汉式
    public static Singleton getsingleton() {
        if(null==singleton) {
            singleton=new Singleton();
            return singleton;
            
        }else {
            return singleton;
        }
        
        
    }
}

猜你喜欢

转载自www.cnblogs.com/mature1021/p/9568607.html