我们有域对象扩展抽象基类以支持时间戳
abstract class TimestampedObject {
private Date timestamp;
public Date getTimestamp(){return timestamp;}
public void setTimestamp(final Date timestamp){this.timestamp = timestamp;}
}
但这会使我们的等级混乱。
我们可以使用Spring AOP介绍或Aspectj ITD来实现这一目标吗?
答案 0 :(得分:1)
AspectJ in Action书中的一个例子(来自未经测试的内存)将会是这样的:
public interface Timestamped {
long getTimestamp();
void setTimestamp();
public static interface Impl extends Timestamped {
public static aspect Implementation {
private long Timestamped.Impl.timestamp;
public long Timestamped.Impl.getTimestamp(){ return timestamp; }
public void Timestamped.Impl.setTimestamp(long in) { timestamp = in; }
}
}
//and then your classes would use it like this:
public class SomeClass implements Timestamped.Impl {
private void someFunc() {
setTimestamp(12);
long t = getTimestamp();
}
}
不确定这本书是否有这种方式,但我通常创建一个单独的Impl接口(如上所示),只扩展主要接口,这样我的一些类可以以不同方式实现时间戳,而无需获取ITD实现。像这样:
public class SomeOtherClass implements Timestamped {
private long myOwnPreciousTimestamp;
public long getTimestamp() {
//Oh! I don't know should I give it to you?!
//I know, I will only give you a half of my timestamp
return myOwnPreciousTimestamp/2;
}
//etc.....
}
答案 1 :(得分:0)