单例模式

2020-06-10  本文已影响0人  寂静的春天1988

饿汉式

public class Student {
    
    private Student() {
        
    }
    
    private static Student s = new Student();
    
    
    public static Student getStudent() {
        return s;
    }
    public static void main(String[] args) {
        Student s1=Student.getStudent();
        Student s2=Student.getStudent();
        System.out.println(s1==s2);
    }
}

懒汉式:使用同步方法

public class Student {
    
    private Student() {
        
    }
    
    private static Student s = null;
    
    
    public synchronized static Student getStudent() {
        if(s==null) {
            s=new Student();
        }
        
        return s;
    }
    public static void main(String[] args) {
        Student s1=Student.getStudent();
        Student s2=Student.getStudent();
        System.out.println(s1==s2);
    }
}

懒汉式:使用同步代码块

public class Student {
    
    private Student() {
        
    }
    
    private static Student s = null;
    
    
    public  static Student getStudent() {
        if(s==null) {
            synchronized(Student.class) {
                if(s==null) {
                    s=new Student();
                }
            }
        }
        
        return s;
    }
    public static void main(String[] args) {
        Student s1=Student.getStudent();
        Student s2=Student.getStudent();
        System.out.println(s1==s2);
    }
}

开发中一般使用:饿汉式

上一篇 下一篇

猜你喜欢

热点阅读