《大话设计模式》第六章
package ch06.b;
public abstract class Component {
public abstract void operation();
}
package ch06.b;
public class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.println("具体对象的操作");
}
}
package ch06.b;
public abstract class Decorator extends Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
if (component != null) {
component.operation();
}
}
}
package ch06.b;
public class ConcreteComponentA extends Decorator {
public ConcreteComponentA(Component component) {
super(component);
}
@Override
public void operation() {
System.out.println("before ConcreteComponentA.operation");
super.operation();
System.out.println("after ConcreteComponentA.operation");
}
}
package ch06.b;
public class ConcreteComponentB extends Decorator {
public ConcreteComponentB(Component component) {
super(component);
}
@Override
public void operation() {
System.out.println("before ConcreteComponentB.operation");
super.operation();
System.out.println("after ConcreteComponentB.operation");
}
}
package ch06.b;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
Component comp = new ConcreteComponentA(new ConcreteComponentB(new ConcreteComponent()));
comp.operation();
//下面是JDK中的装饰器模式的经典例子
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("1.txt");
bos = new BufferedOutputStream(fos);
bos.write(65);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCloseable(bos);
closeCloseable(fos);
}
}
private static void closeCloseable(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
closeable = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行一下代码,输出:
before ConcreteComponentA.operation
before ConcreteComponentB.operation
具体对象的操作
after ConcreteComponentB.operation
after ConcreteComponentA.operation
看看代码,看看JDK,应该就能理解了。