翻看Vector代码的时候,看到这么一段。

/**
* Returns an enumeration of the components of this vector. The
* returned {@code Enumeration} object will generate all items in
* this vector. The first item generated is the item at index {@code 0},
* then the item at index {@code 1}, and so on.
*
* @return an enumeration of the components of this vector
* @see Iterator
*/
public Enumeration<E> elements() {
return new Enumeration<E>() {
int count = 0; public boolean hasMoreElements() {
return count < elementCount;
} public E nextElement() {
synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
throw new NoSuchElementException("Vector Enumeration");
}
};
}

 

 Enumeration是个接口,内部定义此处不缀述。

此处用到了这种new接口的使用方法,如果有些场合,只需要临时需要创建一个接口的实现类,上面的"技巧"可以用来简化代码.
在结合接口内部的方法设定,即可实现强大的处理方式,而省去很多单独处理逻辑问题。 我们在仔细看,会发现实现的接口实例中并没有elementCount,而elementCount是在Vector中定义的,那么如果调用该方法,返回一个接口实例,在使用该接口实例的时候,如何获取到该值?
于是写一个demo查看下,

会发现返回的实例里面维护了一个包含v实例成员变量的实例指向。所以在其方法实现里面可以使用到该值。(至于其如何实现的为探究,读到此文知道的读者可以留言,谢谢)

那么会想,是否返回一个对象都会封装一个此类指向呢,可以自己按照此种方式写一个试试。

Car是一个接口,按照上述方式模式实现的,存在上述所说引用;Student并没有。

总结:

1、适当的时候巧用返回接口实例方式,可结合模式方式实现某种功能简化;

2、是否可以利用其引用处理某些问题,什么样的修饰符的成员变量能被引用对象实现,这种设计的初衷考虑哪些等等,值得神经的时候思考下。

3、另外new 接口方式可以当做参数传递。如t.inject(new Car(){

  接口实现方法;

});

最新文章

  1. webapi - 使用依赖注入
  2. ModernUI教程:创建自定义主题
  3. 第3月第2天 find symbolicatecrash 生产者-消费者 ice 引用计数
  4. Design and Analysis of Algorithms_Fundamentals of the Analysis of Algorithm Efficiency
  5. Clr编写Insert Triggr
  6. 【Vegas原创】vlookup的使用方法
  7. 如何开启SQL Server 2008的远程联机
  8. tty/pts 相关指令
  9. 由chkconfig 引发的联想&mdash;&mdash;怎么查看程序是否已经安装/成功安装
  10. Eclipse 发布到网站的附加产品的形式 Update Site
  11. shp文件显示
  12. Increasing Speed Limits
  13. C#学习笔记——数据库篇(1)
  14. Python-函数小结
  15. docker镜像保存及导出(save,export)
  16. JavaScript数据类型,构造函数
  17. 【dfs】p1451 求细胞数量
  18. (Access denied for user &#39;root&#39;@&#39;slaver1&#39; (using password: YES))
  19. Elasticsearch集群监控工具bigdesk插件安装
  20. NOIP模拟题 2017.11.6

热门文章

  1. PHP读取excel表格,和导出表格
  2. 海思平台交叉编译curl支持SSL功能
  3. Machine Learning——吴恩达机器学习笔记(酷
  4. 20155317 《Java程序设计》0510上课考试博客
  5. 从码云把之前的代码git push 回IDEA 对IDEA里的文件进行简单操作
  6. 在SQL SERVER中批量替换字符串的方法
  7. spring_cloud多个微服务访问时偶发forward_error问题
  8. 180727-时序数据库InfluxDB之备份和恢复策略
  9. 测试基础-http协议(转)
  10. 面试时让你说一个印象最深的bug,该怎么回答