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