答案很简单……我们可以用 2 个类来解决这个问题。
每个类的特点如下
ReportUtil:
(1) 跟踪是否有任何报告以写入模式打开
(2) 根据可用的访问模式创建报表对象
报告:
(1) 根据给定的访问权限打开只读或可写报告
(2) 关闭时,如果当前报表以写入模式打开,则重置 ReportUtil 类中的标志。
客户:
测试 ReportUtil 和 Report 类。
import java.util.LinkedList;
public class ReportUtil {
private static boolean bIsWriteLockAvaialable = true;
public static synchronized Report getReport() {
Report reportObj = new Report(bIsWriteLockAvaialable);
if(true == bIsWriteLockAvaialable) {
bIsWriteLockAvaialable = false;
}
return reportObj;
}
public static void resetLock() {
bIsWriteLockAvaialable = true;
}
}
public class Report {
private boolean bICanWrite = false;
public Report(boolean WriteAccess) {
bICanWrite = WriteAccess;
}
public void open() {
if(bICanWrite == true) {
//Open in write mode
System.out.println("Report open in Write mode");
}
else {
//Open in readonly mode
System.out.println("Report open in Read only mode");
}
}
public synchronized void close() {
if(bICanWrite == true) {
ReportUtil.resetLock();
}
}
}
public class Client {
public static void main(String[] args) {
Report report1 = ReportUtil.getReport();
report1.open(); //First time open in writable mode
Report report2 = ReportUtil.getReport();
report2.open(); //Opens in readonly mode
Report report3 = ReportUtil.getReport();
report3.open(); //Opens in readonly mode
report1.close(); //close the write mode
Report report4 = ReportUtil.getReport();
report4.open(); //Opens in writable mode since the first writeable report was closed
}
}
输出:
以写入模式打开报告
以只读模式打开报告
以只读模式打开报告
以写入模式打开报告
我不知道为什么我们要在这里使用哈希表。可能是我没有理解你的要求。另外,我使用了同步方法来避免同步问题。
如果您的要求是跟踪所有使用该报告的用户,请告诉我。
学习愉快!!!