efault implementation of the add/remove observer lifecycle operations
private List<LifecycleObserver> Lifecycle.observers = new ArrayList<LifecycleObserver>();
public void Lifecycle.addObserver(LifecycleObserver observer) {
observers.add(observer);
}
public void Lifecycle.removeObserver(LifecycleObserver observer) {
observers.remove(observer);
}
AOP@Work:介绍AspectJ 5 - AspectJ中的Java 5支持和其他新特性抢鲜看(4)
时间:2011-09-04 IBM Adrian Colyer
状态管理和事件处理
因为我想在这篇文章中介绍许多基础知识,所以从剩下的方面实现中我只摘录 几个。对于每个生命周期事件,方面都提供 before 和 after returning 建议, 以验证托管组件处于有效状态,从而执行操作并把变化通知给已注册的观察者, 如下所示:
清单 5. 状态管理和通知
// these pointcuts capture the lifecycle events of managed components
pointcut initializing(Lifecycle l) : execution(* Lifecycle.initialize(..)) && this(l);
pointcut starting (Lifecycle l) : execution(* Lifecycle.starting(..)) && this (l);
pointcut stopping(Lifecycle l) : execution(* Lifecycle.stopping(..)) && this(l);
pointcut terminating(Lifecycle l): execution(* Lifecycle.terminating(..)) && this(l);
/**
* Ensure we are in the initial state before initializing.
*/
before(Lifecycle managedComponent) : initializing(managedComponent) {
if (managedComponent.state != State.INITIAL)
throw new IllegalStateException("Can only initialize from INITIAL state");
managedComponent.state = State.INITIALIZING;
}
/**
* If we successfully initialized the component, update the state and
* notify all observers.
*/
after (Lifecycle managedComponent) returning : initializing(managedComponent) {
managedComponent.state = State.INITIALIZED;
for (LifecycleObserver observer: managedComponent.observers)
observer.componentInitialized(managedComponent);
}
注意建议体中使用了新风格的 for 循环,对所有已注册的观察者进行迭代。 如果生命周期操作正常返回,就执行 after returning 建议。如果生命周期操作 通过运行时异常而退出,那么后面的建议(清单 6)就把组件转变成 BROKEN 状 态。可以想像,方面中会有进一步的建议,防止对状态是 BROKEN 的托管组件执 行任何操作,但是这个讨论超出了这篇文章的范围:
清单 6. 故障检测和到 BROKEN 状态的转变
/**
* If any operation on a managed component fails with a runtime exception
* then move to the broken state and notify any observers.
*/
after(Lifecycle managedComponent) throwing(RuntimeException ex) :
execution (* *(..))
&& this(managedComponent) {
managedComponent.state = State.BROKEN;
for (LifecycleObserver observer: managedComponent.observers)
observer.componentBroken(managedComponent);
}
示例方面已经表明,在方面中使用 Java 5 特性,就像在类中使用它们一样简 单。而且从匹配的角度来看,根据注释的存在与否(在 declare parents 语句中 ),示例方面 |