Collections.unmodifiableList()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lxy344x/article/details/74011348

Collections.unmodifiableList()-只读集合

public class Student {
    private String name;

    private ArrayList<String> courses;

    public Student(String name, ArrayList<String> courses) {
        this.name = name;
        this.courses = courses;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void addCourse(String course) {
        courses.add(course);
    }

    public String removeCourse(String course) {
        boolean removed = courses.remove(courses);

        if (removed) {
            return course;
        } else {
            return null;
        }
    }

    public List<String> getCourses() {
        return Collections.unmodifiableList(courses);
    }
}

如何限制实体的访问权限,在聚合内部封装聚合自身的状态。防止外部对其不合法操作,比如如果想限制学生课程的修改,一般的做法直接利用java bean的添加setCourse,如果被调用则抛出不可修改的异常。所以在student内部不再提供setCource方法,直接使用addCourse添加课程,并由getCourse获取只读状态下的集合。

猜你喜欢

转载自blog.csdn.net/lxy344x/article/details/74011348