变量上下文(ActionContext)也是一个栈,使用栈可以实现局部变量、全局变量和传递参数等功能,由于变量上下文的栈操作是完全开放的,因此可以在动作中使用。
变量上下文的栈操作必须要谨慎,最低要求是push和pop必须成对出现,并且用try{}finally{},pop操作在finally中。
Bindings bindings = actionContext.push();
try{
     .......
}finally{
     actionContext.pop();
} 
     对变量上下文的栈操作其实是比较少见的,一般在框架里用的比较多,比如SWT界面模型框架,模型的主要功能是实现create方法,通过create方法创建SWT的Java对象。
另外一个界面是由各种控件组成的,而控件之间存在包含关系(父子关系),因此在SWT的API中一个控件通常需要传入parent(父)控件,如Button的构造函数。
Button(Composite parent, int style)
这样在SWT的模型框架里,就可以使用栈来传入parent变量。
//构造SWT对象
Button button = new Button(parent, SWT.NONE);
//执行Button的子模型
Bindings bindings = actionContext.push();
try{
    bindings.put("parent", button);
    for(Thing child : self.getChilds()){
        child.doAction("create", actionContext);
    }
}finally{
    actionContext.pop();
} 
     使用以上方法可以解决任意控件模型的嵌套情况。
Copyright © 2007-2014 XWorker.org 版权所有