HIT软件构造Lab2关于ADT与OOP的感悟

本次实验分为两个任务,两个任务互有联系,个人感觉很有趣味性

  本次实验中老师提供了我们所需实现的接口,也就是说接口功能是已经固定好的(据说在以后的实际工作中架构师的任务就是想好这种大体的框架)

以上为部分截图:)

值得注意的是为了增强代码的复用性而采用了泛型编程的技术

接下来是第一部分任务的感想

第一部分首先要求我们采用两种套路实现这个graph接口,一种是图中的元素为点,另一种是图中的元素为边

个人感觉难度一般,上学期学的《数据结构》感觉在此刻派上了用场。感觉还是比较满意的

而以上可以算作任务的前期准备阶段,在graphpoet这个任务中我感觉自己有点体会到了面向对象编程的魅力了,要是用之前所学的C语言编写此任务的话,我一定会感到无所适从,且不说这次要求实现的功能比较复杂,就是在java中使用的现成的map,list ,set容器如果用C语言再实现的话工作量会大大加大,而且可能会陷入重复造轮子的境地

 

而在第一部分完成后,第二部分的难度也就骤然下降了

 1     /**
 2      * Generate a poem.
 3      * 
 4      * @param input string from which to create the poem
 5      * @return poem (as described above)
 6      */
 7     public String poem(String input) {
 8         List<String> te = new ArrayList<>(Arrays.asList(input.split(" ")));
 9         List<String> newstring = new ArrayList<>();
10         for (int i=0;i<te.size() - 1;i++){
11             newstring.add(te.get(i));
12             Map<String,Integer> ta1 = graph.targets(te.get(i));
13             Map<String,Integer> ta2 = new HashMap<>();
14             for (String a:ta1.keySet()){
15                 if (graph.targets(a).containsKey(te.get(i+1)))
16                     ta2.put(a,ta1.get(a)+graph.targets(a).get(te.get(i+1)));
17             }
18             int c = -1;                                         //找出权值最大的
19             String tee = null;
20             for (String b:ta2.keySet()){
21                 if (ta2.get(b)>c){
22                     tee = b;
23                     c=ta2.get(b);
24                 }
25             }
26             if (tee!=null)
27                 newstring.add(tee);
28         }
29         newstring.add(te.get(te.size()-1));
30         String last=new String();
31         for (int i=0;i<newstring.size()-1;i++)
32             last = last+newstring.get(i)+" ";
33         last = last+newstring.get(newstring.size()-1);
34         CheckRep();
35         return last;
36     }

 

只需要短短的三十余行代码,就可以实现graphpoet的核心功能

 

通过对Lab2的实现,我感觉面向对象编程确实是一种伟大的思想,通过它可以大大提高效率,尤其是在编写大规模代码时,通过OOP以及ADT的合理使用,我们能够极大提高工作效率与代码安全性

posted @ 2022-06-03 01:10  HITyfj  阅读(47)  评论(0)    收藏  举报