我们在前一个项目中实现了报告的生成过程。我们将在本项目中使用代理模式实现记录并提交报告的功能。
首先,在StudentCenter类中新创建一个成员方法submitReport()。该方法接收两个参数,第一个是Student对象,表示提交报告的学生对象;第二个参数是Report对象,即提交的报告。
public class StudentCenter {
public void submitReport(Student theStudent, Report theReport);
}
我们再在com.littlewaterdrop.report包中创建一个新接口ReportSubmission。该接口包含一个成员方法submit()。该方法接收两个参数,第一个是Student对象,表示提交报告的学生对象;第二个参数是Report对象,即提交的报告。
public interface ReportSubmission {
void submit(Student theStudent, Report theReport);
}
在StudentCenter类中新增一个成员变量reportSubmitter,类型为ReportSubmission,用于提交报告。
在第二个步骤中,我们实现一个简单的类SaveReport,它实现了ReportSubmission接口。它的submit()方法将Report对象保存在一个文件中。其实现的逻辑如下面的代码所示,文件名称可以以学生对象的id命名。
public class SaveReport implements ReportSubmission {
public void submit(Student theStudent, Report theReport) {
try {
Files.writeString(Path.of(theStudent.getId()), theReport.getContent(), StandardOpenOption.CREATE);
} catch(IOException ex) {
System.err.println("Hmm, something went wrong");
}
}
}
为了跟踪每个学生提交报告的事件,例如,记录提交时间等信息,我们还需要记录日志的功能,即在学生提交报告时,我们需要记录一条记录。例如,当学生James提交了报告时,我们记录一条消息"James submits a report at 2021-03-09 09:00:00"。
因此,在此时,我们可以使用代理模式来实现日志记录功能。我们在com.littlewaterdrop.report包中创建一个新类ReportSubmissionLogging,它实现了接口ReportSubmission。在ReportSubmissionLogging中,我们需要一个成员变量realObj,ReportSubmitter类型,指向真实提交报告功能的类。
public class ReportSubmissionLogging implements ReportSubmission {
private ReportSubmission realObj = null;
...
}
在submit()方法中,ReportSubmissionLogging需要首先记录一条日志信息,然后再调用realObj对象的方法submit(),完成真实报告的提交。