首先有一个简单业务接口:
public String doExecute(String in);
}
这个接口有一个业务对象类的实现。
public String doExecute(String in) {
System.out.println( " Here in MyBusinessObject doExecute: input : " + in);
return in;
}
}
protected IMyBusinessObject target;
public void setTarget(IMyBusinessObject target) {
this .target = target;
}
public ADecorator(){};
public ADecorator(IMyBusinessObject target_) {
setTarget(target_);
}
}
public DebugConcreteDecorator(IMyBusinessObject target_) {
super (target_);
}
public String doExecute(String in) {
System.out
.println( " DebugConcreteDecorator: before method : doExecute " );
String ret = target.doExecute(in);
System.out.println( " DebugConcreteDecorator: after method : doExecute " );
return ret;
}
}
现在在客户端,我们调用业务对象:





Here in MyBusinessObject doExecute: input :Hello World
DebugConcreteDecorator: after method : doExecute
public AnotherConcreteDecorator(
IMyBusinessObject target_) {
super (target_);
}
public String doExecute(String in) {
System.out
.println( " AnotherConcreteDecorator: Going to execute method : doExecute " );
in = in + " Modified by AnotherConcreteDecorator " ;
String ret = target.doExecute(in);
System.out
.println( " AnotherConcreteDecorator: After execute method : doExecute " );
return ret;
}
}
上面的代码片段通过在业务方法输入的字符参数后增加(" Modified by AnotherConcreteDecorator")字符串,从而实现对其进行了修改。如果我们想链化装饰器,在客户端,我们可以编写如下的代码:




在上面的代码片段中,我在创建一个DebugConcreteDecorator实例时,向其传递了一个实际的业务对象实例。然后用一个刚才定义的notherConcreteDecorator实例去包装DebugConcreteDecorator实例。AntherConcreteDecorator首先在输入参数后增加字符串对其进行修改,然后调用DebugConcreteDecorator实例的doExecute()方法。这时,DebugConcreteDecorator会记录doExectute()方法的输出的条目,然后调用doExecute()去调用实际业务对象的doExecute()方法。
它的返回路径以相反的顺序。在从实际的业务对象(MyBusinessObject)doExecute()方法返回之后,DebugConcreteDecorator余下代码将被执行。于是,调用返回至AnotherConcreteDecorator实例并执行余下的部份代码。
输出结果如下:
DebugConcreteDecorator: before method : doExecute
Here in MyBusinessObject doExecute: input :Hello World Modified by AnotherConcreteDecorator
DebugConcreteDecorator: after method : doExecute
AnotherConcreteDecorator: After execute method : doExecute