现在的位置: 首页 > 综合 > 正文

Annotation PK Interface

2012年08月24日 ⁄ 综合 ⁄ 共 1613字 ⁄ 字号 评论关闭

Interface在OO中处于核心地位,针对接口编程更是OOP的核心原则之一,但即使将该原则贯彻到底的COM/CORBA,依然面对大量的依赖、耦合,牵一接口而动全部客户的修改

另一方面,Hurb Sutter说各种编程范式,包括面向对象,核心都是某种管理依赖性,降低依赖性的技术,那么.Net Attribute, XDoclet, Java Annotation代表的Attribute Oriented Programming在降低依赖性上又前进了多少呢?

以Java Annotation为例,与Java Interface做个对比

1,调用方式

实现Interface的类 被Annotation标注的类
Call by Signature:就像现实生活中的螺丝螺母,插座插头,必须完全吻合 Call by Semantics:就像卡西利亚斯被罚下,临时指定肥罗当守门员一样,肥罗并不需要实现GateKeeper接口,只需临时被标记为具有GateKeeper属性,便可以合法的禁区内手球

2,名称冲突(可看作是对函数签名的依赖,当然,无论Annotation还是Interface,都不允许存在完全相同的全名)

实现Interface的类 被Annotation标注的类
Yes,无法解决从多个接口继承来的方法具有相同签名不同语义的问题 No,Annotation是类型,不会存在完全相同的全名

3,编译时依赖(对Annotation或Interface的依赖)

Annotation Interface
被Annotation标注的类 使用了Annotation的客户 不使用Annotation的客户 实现Interface的类 使用Interface的客户 不使用Interface的客户
Yes Yes No,只要“被Annotation标注的类”已经被编译为bytecode,如以jar包的形式存在,那么使用了该类,但没有用到Annotation的客户,编译时不需要依赖Annotation所在的Jar包 Yes Yes Yes,即使客户没有用到该类所实现的所有接口,编译时该类涉及的所有接口的定义必须可见

4,运行时依赖(对Annotation或Interface的依赖)

Annotation Interface
被Annotation标注的类 使用了Annotation的客户 不使用Annotation的客户 实现Interface的类 使用Interface的客户 不使用Interface的客户
No(即使RetentionPolicy是RUNTIME,我的测试中也是不依赖Annotation的,只要客户不涉及Annotation,但我不确定RUNTIME的真正含义是什么) Yes No(其实运行时对Annotation的依赖被转移到了客户) Yes Yes Yes

5,对Annotation或Interface本身更改的依赖

Annotation Interface
被Annotation标注的类 使用了Annotation的客户 不使用Annotation的客户 实现Interface的类 使用Interface的客户 不使用Interface的客户
Yes Yes No Yes Yes No

6,对“被Annotation标注的类不再被标注”或“实现Interface的类不再实现Interface”这类更改的依赖

Annotation Interface
被Annotation标注的类 使用了Annotation的客户 不使用Annotation的客户 实现Interface的类 使用Interface的客户 不使用Interface的客户
Yes No No Yes Yes No

 

总共 5 处被蓝色字体标注的地方,也就是Annotation在降低依赖性上优于Interface的 5 个方面,也算更接近于“你不需要为你用不到的东西付出代价”这一语言和库的设计理念

当然,Annotation有其它的代价,几个潜在的可能就是“使用方便性”和“性能” 

抱歉!评论已关闭.