博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Refactoring: Encapsulate Collection
阅读量:7003 次
发布时间:2019-06-27

本文共 1474 字,大约阅读时间需要 4 分钟。

hot3.png

今天看NFS-RPC的源码,看到有这样的代码:Collections.unmodifiableList(servers);突然想起来自己之前看重构时的一种叫Encapsulate Collection的思想,今天以代码为主线再来回顾下:

public class Company {	private String companyName;//the name of company	private List
clerkList;//the clerk list //companyName,clearList getter and setter method ........}

我们封装了一个公司类,公司类中包含一个公司名和公司员工的属性,其中公司员工使用List存放。看似完美,然后我们在其他地方使用Company这个类:

Company company = new Company();	List
list = company.getClerkList(); list.add("guolei");

有没有发现什么怪异的地方?在我们获得list的引用后,可以直接操作list,而无需通过company对象。在面向对象的角度来看,这是不正确的设计思想。同样这样的代码看起来也不优雅。这个时候我们引出Collections.unmodifiableList()方法,这个方法的作用是:

Returns an unmodifiable view of the specified collection.

也就是返回一个集合,这个集合就像我们数据库的视图一样,只能read,而不能write。

好了,现在我开始改编我的那个不太优雅的Company类:

public class Company {	private String companyName;//the name of company	private List
clerkList = new ArrayList
();//the clerk list public void setCompanyName(String companyName) { this.companyName = companyName; } /** * return a view of clerkList * clerk list */ public List
getClerkList() { return Collections.unmodifiableList(clerkList); } /** * add a clerk * @param clerkName */ public void addClerk(String clerkName){ clerkList.add(clerkName); } /** * remove the clerk * @param clerkName */ public void removeClerk(String clerkName){ clerkList.remove(clerkName); }}

利用Collections的视图方法后,代码变的更加优美,更加健壮。

转载于:https://my.oschina.net/xishuixixia/blog/67033

你可能感兴趣的文章