posts - 56, comments - 77, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Annotation PK Interface

Posted on 2005-09-16 08:19 切尔斯基 阅读(2413) 评论(3)  编辑  收藏

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有其它的代价,几个潜在的可能就是“使用方便性”和“性能”


评论

# re: Annotation PK Interface  回复  更多评论   

2005-09-16 15:02 by 白衣
把使用者接口 PK掉是框架号称无侵入的基础哦。
Spring的做法是绕一个xml文件来定义,比如定义init-method 来 PK 自己的InitializingBean接口--afterPropertiesSet()函数.

现在又多了annotation这种方式,和annotation和xml的PK.....

# re: Annotation PK Interface  回复  更多评论   

2005-09-16 15:20 by 切尔斯基
如果能解决Source Code和Xml同步的问题(如设置init-method为void init(),过了两天代码中void init()被改为void before(),这时需要手工修改配置.xml),或者本质上满足:

1, Annotation和被Annotation的对应被解释执行(意味着修改后不必重新编译)
2, Annotation和被Annotation的对应被自动同步(在任何一方修改后)

侵入性就更少了;

另外一种无侵入框架的技术是模板啊,呵呵,see see:
http://blog.csdn.net/chelsea/archive/2005/08/05/446298.aspx

# re: Annotation PK Interface  回复  更多评论   

2005-12-21 04:33 by ajooo
annotation也仍然要客户代码import这个annotation。除非该annation是标准,比如Renetion之类,否则仍然不爽。

这点上,annoation不如xml。annotation你还需要给他贴上“守门员”标签才行。而在xml中放meta data就相当于教练随心所欲,想让谁当守门员谁就是守门员。

只有注册用户登录后才能发表评论。


网站导航: