可以先了解前期知识点内容https://editor.csdn.net/md?articleId=129809307
什么是单例设计模式?
- 所谓类的单例设计模式,就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。
- java.lang.Runtime就是经典的单例模式。
单例模式有哪些方式
- 饿汉式、懒汉式。也可以通过枚举、静态内部类模拟。
- 二者最主要的区别:创建对象的时机不同。
- 1)饿汉式:由于类加载就创建了对象实例,所以造成了资源浪费,不存在线程安全问题。
- 2)懒汉式:在具体使用时才会创建对象实例,不存在浪费资源,但存在线程安全问题,解决方法(双重检验锁),具体实现下方代码进行展示。
单例模式的实现步骤:
- 将构造器进行私有化操作。(防止new操作创建出对象实例)
- 在类的内部创建对象。
- 提供一个公共的静态方法用于获取对象。
饿汉式
public class SingleTon01 {
public static void main(String[] args) {
// GirlFriend xh = new GirlFriend("小红");
// GirlFriend xb = new GirlFriend("小白");
//通过方法可以获取对象
GirlFriend instance = GirlFriend.getInstance();
System.out.println(instance);
GirlFriend instance2 = GirlFriend.getInstance();
System.out.println(instance2);
System.out.println(instance == instance2);//T
//System.out.println(GirlFriend.n1);
//... }
}
//有一个类, GirlFriend
//只能有一个女朋友
class GirlFriend {
private String name;
//public static int n1 = 100;
//为了能够在静态方法中,返回 gf 对象,需要将其修饰为 static
private static GirlFriend gf