class Athlete { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } // ...... }
而如果是一个Set/List/Map或数组,应该:
[1]初始化这个集合类;
[2]提供对单个元素的add/remove;
[3]提供加入另一个集合的方法。如果是基于此初始化,则先保证当前集合无元素;
[4]对于getter方法,应该返回该集合的只读试图;
[5]提供当前集合size。
public class Game { private Set<Athlete> players = new HashSet<Athlete>();// 1 public void addPlayer(Athlete one) {// 2 players.add(one); } public void removePlayer(Athlete one) {// 2 players.remove(one); } public void addPlayers(Set<Athlete> set) {// 3 Iterator<Athlete> iter = set.iterator(); while (iter.hasNext()) addPlayer(iter.next()); } public void initializaPlayers(Set<Athlete> set) {// 3 if (getAttendNumbers() > 0) players.clear(); players.addAll(set); } public Set<Athlete> getAllPlayers() {// 4 return Collections.unmodifiableSet(players); } public int getAttendNumbers() {// 5 return players.size(); } }C#:1、普通集合的方法AsReadOnly返回值是一个集合的引用,但是只读属性,这用一个指向常量的指针(指针常量)很好理解,指针所指对象不一定是常量,但用这个指针(指针常量)去引用的时候,系统就认为是个常量,从而实现只读的效果C++:
I have a class which has a private attribute vector rectVec;
class A {
private:
vector<Rect> rectVec;
};
My question is how can I return a 'read-only' copy of my Vector? I am thinking of doing this:
class A {
public:
const vect<Rect>& getRectVec() { return rectVect; }
}
That is the right way, although you'll probably want to make the function const as well.
class A {
public:
const vect<Rect>& getRectVec() const { return rectVect; }
};
This makes it so that people can call getRectVec using a const A object.