JAVA单例模式

单例,顾名思义就是某一个类在整个程序系统中有且仅有一个实例,称为单例。单例能被整个程序系统访问。创建单例的时候应该使用类方法创建,因为让类的实例去生成另一个唯一的实例变得毫无意义.

饿汉式

package com.hc;

public class Test {

    public static void main( String[] args){    

        Singleton1 single1 = Singleton1.getInstance();
        Singleton1 single2 = Singleton1.getInstance();
        
        System.out.println("single1"+single1);
        System.out.println("single2"+single2);

        
    }
}

/*
static修饰的常量会在构造方法加载时加载,因此在使用到类Singleton1的时候
就会加载构造方法,同时private static Singleton1 singleton1 = new Singleton1();就实例就创建了,
并且static修饰的变量只会创建一次,在程序中只有一份内存
*/
class Singleton1 {
    
    private static Singleton1 singleton1 = new Singleton1();

    private Singleton1(){
        System.out.println("构造方法");
    }
    
    public static Singleton1 getInstance(){
        return singleton1;
    }
}

懒汉式

package com.hc;

public class Test {

    public static void main( String[] args){    

        Singleton1 single1 = Singleton1.getInstance();
        Singleton1 single2 = Singleton1.getInstance();
        
        System.out.println("single1"+single1);
        System.out.println("single2"+single2);

        
    }
}

class Singleton1 {
    
    private static Singleton1 singleton1 = null;

    private Singleton1(){
        System.out.println("构造方法");
    }
    
    public static Singleton1 getInstance(){
        if(singleton1 == null){
            singleton1 = new Singleton1();
        }
        return singleton1;
    }   
}

你可能感兴趣的:(JAVA单例模式)