package com.syh.demo;
/**
* 单例设计模式
*/
public class Singleton {
//1.私有化构造方法,使用private关键字修饰
private Singleton() {
}
//2.声明本类类型的引用指向本类类型的对象,对外提供,且只提供一个对象
private static Singleton instance = new Singleton(); //饿汉式(推荐使用)
//3.提供公有的get方法负责将上述对象返回出去
public static Singleton getInstance() {
return instance;
}
/*private static Singleton instance = null; //懒汉式(存在多线程的问题)
public static Singleton getInstance() {
if(null == instance){
instance = new Singleton();
}
return instance;
}*/
/**
* 最好新创建一个测试类
*/
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println("比较结果为:" + (singleton1 == singleton2)); //true
}
}
单例设计模式(饿汉式)
于 2022-01-19 09:44:58 首次发布