场景1:
我正在编写一份报告,以了解更多部门在研究所的表现和参与情况。当我在GUI中显示报告时,它可以根据部门表现和参与情况(参与的学生人数)进行排序。
- 对于这个场景,我应该使用原型设计模式吗
例如:
public abstract class Report implements Cloneable {
private String id;
protected String type;
public void setId(String id){
id=id;
}
public String getId(){
return id;
}
public String getType(){
return type;
}
abstract void getReportData();
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
public class PerformanceReport extends Report {
public PerformanceReport(){
type = "Performance";
}
@Override
public void getReportData() {
/* Get report data from database and sort based on performance*/
}
}
public class ParticipationReport extends Report {
public ParticipationReport(){
type = "Participation";
}
@Override
public void getReportData() {
/* Get report data from database and sort based on participation*/
}
}
public class ReportCache {
private static Hashtable<String, Report> reportMap = new Hashtable<String, Report>();
public static Report getReport(String reportid) {
Report cachedReport = reportMap.get(reportid);
return (Report) cachedReport.clone();
}
public static void loadCache() {
ParticipationReport participationReport = new ParticipationReport();
participationReport.setId("1");
reportMap.put(report.getId(),report);
PerformanceReport performanceReport = new PerformanceReport();
performancenReport.setId("2");
reportMap.put(report.getId(),report);
}
}
public class PrototypePatternReport {
public static void main(String[] args) {
ReportCache.loadCache();
Report clonedReport = (Report) ReportCache.getReport("1");
System.out.println("Report : " + clonedReport.getType());
Report clonedReport2 = (Report) ReportCache.getReport("2");
System.out.println("Report : " + clonedReport2.getType());
}
}
- 我的上述概念是正确的吗?这个概念和原型模式有关吗
场景2:
我将测验细节(问题和选项,答案)存储在一个对象中,当学生请求测验时,我应该加密答案并给出。对于加密的答案,我应该保留另一个对象来给出。在这种情况下,我可以使用原型吗?在收到学生的回复后,我应该将学生的回答与现有对象进行比较。
当对象初始化成本高昂或明确需要一个对象是另一个对象的副本时,原型模式通常很有用。
场景1:在您的情况下,从数据库中获取报表数据并对其进行排序比实例化对象要贵得多,而且每个报表都由自己的数据组成(从另一个对象复制不会让您受益),所以我不会考虑使用原型。
场景2:在这种情况下,关键是
对于加密的答案,我应该保留另一个对象来给出
在这种情况下,由于您需要另一个对象,并且需要确保第二个对象是第一个对象的精确副本,因此可以使用原型创建第二个物体,然后更改其属性以确保隐藏答案。