单例模式Singleton介绍
- 定义
在java核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例
- 实现思路
将该类的构造方法定义为私有方法,这样其他处的代码就无法通过调用该类的构造方法来实例化该类的对象,只有通过该类提供的静态方法来得到该类的唯一实例;
在该类内提供一个静态方法,当我们调用这个方法时,如果类持有的引用不为空就返回这个引用,如果类保持的引用为空就创建该类的实例并将实例的引用赋予该类保持的引用。
- Lazy Initialization
- 单例的实例在第一次被使用时创建,而不是在类加载时就立即创建。
- 由于它在多线程环境下可能会导致多个实例被创建,因此不推荐在多线程环境中使用
- 为了解决同步开销问题,可以使用双重检查锁定机制。这种方式只在instance为null时才进行同步。
- 举例(maven)版
实现遍历文件夹下所有excel文件的时间对比
一、在pom.xml文件中插入如下代码块
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version> <!-- 使用最新的稳定版本 -->
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version> <!-- 使用最新的稳定版本 -->
</dependency>
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- Apache POI for Excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<!-- Jackson for JSON parsing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4.2</version>
</dependency>
</dependencies>
三、创建ExcelFileManager java类
java">package com.test_Ana;
import java.io.*;
public class ExcelFileManager {
// 私有静态变量,持有类的唯一实例
private static volatile ExcelFileManager instance;
// 私有构造函数,防止外部直接创建对象
private ExcelFileManager() {}
// 公共静态方法,返回类的唯一实例
public static ExcelFileManager getInstance() {
if (instance == null) { // 第一次检查
synchronized (ExcelFileManager.class) {
if (instance == null) { // 第二次检查
instance = new ExcelFileManager();
}
}
}
return instance;
}
// 方法来遍历文件夹中的所有Excel文件
public void traverseExcelFiles(String folderPath) {
long startTime = System.currentTimeMillis(); // 记录开始时间
File folder = new File(folderPath);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null) {
for (File file : listOfFiles) {
if (file.isFile() && file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
// 处理Excel文件,例如读取内容等
System.out.println("Processing: " + file.getName());
}
}
}
long endTime = System.currentTimeMillis(); // 记录结束时间
System.out.println("Time taken: " + (endTime - startTime) + " ms"); // 输出运行时间
}
}
三、在main中调用ExcelFileManager类
java">package com.test_Ana;
public class Main {
public static void main(String[] args) {
// 假设你的Excel文件存放在D:\ExcelFiles路径下
String folderPath = "C:\\Users\\17435\\Desktop\\temp";
ExcelFileManager excelFileManager = ExcelFileManager.getInstance();
excelFileManager.traverseExcelFiles(folderPath);
}
}
运行结果如下: