笔记

way

Beginning JO(2 Collection)

    数组可以装基本类型或者引用,collections只能装引用。
    通常有两种方法可以扩展collection 来满足一些需要:继承某种集合类型和封装某种集合类型。第一种的优点是初始化的时候在内存中只产生一个对象,这是继承特性决定的。后者的优点是我们可以方便控制被封装集合的各种属性。
Whenever possible, it’s desirable to bury implementation details inside of a class rather than exposing client code to such details。例:
法1:
public class Student {
    private String name;
    private String studentId;  
    private ArrayList<TranscriptEntry> transcript; //成绩报告单
    public void addTranscriptEntry(TranscriptEntry te) {   // 操作transcript达到记录成绩
        // Store the TranscriptEntry in our ArrayList.
        transcript.add(te);
    }
}
客户端调用代码:
Student s = new Student("1234567", "James Huddleston");
Course c = new Course("LANG 800", "Advanced Language Studies");
TranscriptEntry te = new TranscriptEntry(c, "Fall 2006", "B+");
s.addTranscriptEntry(te);
法2:
建立新对象,封装一个ArrayList:
public class Transcript {
    private ArrayList<TranscriptEntry> transcriptEntries;
    public void courseCompleted(Course c, String semester, String grade) {
        // Instantiate and insert a brand-new TranscriptEntry object into the
        // ArrayList - details hidden away!
        transcriptEntries.add(new TranscriptEntry(c, semester, grade);
    }
}
public class Student {
    private String name;
    private String studentId;
    // This used to be declared as an ArrayList.
    private Transcript transcript;
    // etc.
}
客户端代码:
s.courseCompleted(c, "Spring 2006", "A+");
第二种方法使Student处理更少的细节,不用管transcripts怎么表达,看不到TranscriptEntry的存在。客户端代码更简单。

posted on 2009-12-10 11:38 yuxh 阅读(156) 评论(0)  编辑  收藏 所属分类: jdkOO设计


只有注册用户登录后才能发表评论。


网站导航:
 

导航

<2009年12月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

统计

常用链接

留言簿

随笔分类

随笔档案

收藏夹

博客

搜索

最新评论

阅读排行榜

评论排行榜