[java]代码库
/**
* 对修改关闭,对扩展开放。
*
* 统一接口
*/
interface Filterable {
public void filter();
}
/**
* 目标类
*/
class Filter implements Filterable {
@Override
public void filter() {
System.out.println("目标类的核心过滤方法...");
}
}
/**
* DecoratorForFilter1包装类与目标类实现相同的接口 --> 织入Log
*/
class DecoratorForFilter1 implements Filterable {
private Filterable filterable;
public DecoratorForFilter1(Filterable filterable) {
this.filterable = filterable;
}
private void beforeMethod() {
System.out.println("DecoratorForFilter1 --> 核心过滤方法执行前执行");
}
private void afterMethod() {
System.out.println("DecoratorForFilter1 --> 核心过滤方法执行后执行");
}
@Override
public void filter() {
beforeMethod();
filterable.filter();
afterMethod();
}
}
/**
* DecoratorForFilter2包装类与目标类实现相同的接口 --> 织入Log
*/
class DecoratorForFilter2 implements Filterable {
private Filterable filterable;
public DecoratorForFilter2(Filterable filterable) {
this.filterable = filterable;
}
private void beforeMethod() {
System.out.println("DecoratorForFilter2 --> 核心过滤方法执行前执行");
}
private void afterMethod() {
System.out.println("DecoratorForFilter2 --> 核心过滤方法执行后执行");
}
@Override
public void filter() {
beforeMethod();
filterable.filter();
afterMethod();
}
}
/**
* 客户端测试类
*
* @author Leo
*/
public class Test {
public static void main(String[] args) {
/**
* 目标对象
*/
Filterable targetObj = new Filter();
/**
* 包装对象(对目标对象进行包装)
*/
Filterable decorObj = new DecoratorForFilter1(new DecoratorForFilter2(
targetObj));
/**
* 执行包装后的业务方法
*/
decorObj.filter();
}
}//源代码片段来自云代码http://yuncode.net