java 设计模式 单例模式之饿汉模式/懒汉模式 singleton pattern

https://v.qq.com/x/page/e0364ung5zp.html

 讲的不错, 关于 饿汉式单例模式

code

Student 类:

package com.test;
//单例模式之       饿汉     模式 eager singleton
public class Student {
    //构造函数私有,别人无法 new 实例
    private Student(){}
    //自己造一个实例
    private static Student student = new Student();//饿汉模式:直接 new 了一个 instance。线程安全
    public static Student getStudent()
    {
        return student;
    }
}

 
测试类:
package com.test;
//单例模式,保证类在内存中只有一个实例
public class StudentTest {
    public static void main(String[] args) {
        Student student1 = Student.getStudent();
        Student student2 = Student.getStudent();
        System.out.println(student1);
        System.out.println(student2);
        System.out.println(student1 == student2);
    }
}

======结果===========
com.test.Student@7852e922
com.test.Student@7852e922
true
 

 上面是  饿汉式 单例模式。

 

下面看看懒汉式:

 Person 类:

package com.test;
//单例模式之       懒汉    模式  lazy singleton
public class Person {
    private Person() {};
    private static Person person; //懒汉模式并不直接 new instance
    
    public static Person getInstance()
    {
        if (person == null) //这里其实不是线程安全的。后续可以 enhance
        {

            person = new Person();

            return person;//只有当调用getInstance的时候,才回去初始化这个单例。
        }
        return person;
    }
}

 测试类:

package com.test;
public class PersonDemo {
    public static void main(String[] args) {
        Person person1 = Person.getInstance();
        Person person2 = Person.getInstance();
        System.out.println(person1 == person2);
    }
}

 =======总结==========

饿汉就是类一旦加载,就把单例初始化完成,保证getInstance的时候,单例是已经存在的了。
而懒汉比较懒,只有当调用getInstance的时候,才回去初始化这个单例。

饿汉式天生就是线程安全的,可以直接用于多线程而不会出现问题,

懒汉式本身是非线程安全的,为了实现线程安全有几种写法。

package com.test;
//单例模式之       懒汉    模式  lazy singleton
public class Person {
    private Person() {};
    private static Person person; //懒汉模式并不直接 new instance
    
    public static synchronized  Person getInstance() //这里加上 synchronized 保证线程安全
    {
        if (person == null)
        {
            person = new Person();//只有当调用getInstance的时候,才回去初始化这个单例。
            return person;

        }
        return person;
    }
}

 
原文地址:https://www.cnblogs.com/backpacker/p/10946248.html