Encapsulate collections
来源:互联网 发布:同步看电视的软件 编辑:程序博客网 时间:2024/06/16 05:02
http://www.javapractices.com/topic/TopicAction.do?Id=173
In general, Collections are not immutable objects. As such, one must often exercise care that collection fields are not unintentionally exposed to the caller.
One technique is to define a set of related methods which prevent the caller from directly using the underlying collection, such as:
- addThing(Thing)
- removeThing(Thing)
- getThings() - return an unmodifiable Collection
import java.util.*;public final class SoccerTeam { public SoccerTeam(String aTeamName, String aHeadCoachName){ //..elided } public void addPlayer(Player aPlayer){ fPlayers.add(aPlayer); } public void removePlayer(Player aPlayer){ fPlayers.remove(aPlayer); } public Set<Player> getPlayers(){ return Collections.unmodifiableSet(fPlayers); } //..elided // PRIVATE private Set<Player> fPlayers = new LinkedHashSet<>(); private String fTeamName; private String fHeadCoachName;}
Example 2
BaseballTeam is an example of exposing the collection directly to the caller. This is not necessarily an incorrect design, but it's riskier, since the contents of the collection can be directly changed by both BaseballTeam and its caller:
import java.util.*;public final class BaseballTeam { public BaseballTeam(String aTeamName, String aHeadCoachName){ //..elided } public void setPlayers(Set<Player> aPlayers){ fPlayers = aPlayers; } public Set<Player> getPlayers(){ return fPlayers; } //..elided // PRIVATE private Set<Player> fPlayers; private String fTeamName; private String fHeadCoachName;}
0 0
- Encapsulate collections
- Encapsulate Field(封装值域)
- Encapsulate Collection(封装群集)
- Define encapsulate class type
- Encapsulate Behavior, not Just State
- Encapsulate Behavior, Not Just State
- Collections
- Collections
- Collections
- collections
- Collections
- COLLECTIONS
- Collections
- Collections
- collections
- Collections
- Collections
- collections
- 是完全平方数的有序数对
- 关于使用js进行表单提交操作引发的表单重复提交问题
- nyist504
- linux下简单的socket编程
- 经典排序算法之——快速排序
- Encapsulate collections
- cocos2d:如何优雅的管理游戏资源
- windows7打开chm文件,不显示内容的解决
- Java并发基础构建模块简介
- Iterate without an index
- typedef的用法总结
- String 对象 与 StringBuilder 对象的比较.....
- 在Oracle库上几种特殊情况的SQL语句
- Java的正则表达式的基本语法(不全)