1. Java中装饰模式(Decorator)
class="Component.java" name="code">
public interface Component{
public void doSomething();
}
public class ConcreteComponent implements Component{
@Override
public void doSomething(){
System.out.println("功能A");
}
}
public class Decorator implements Component{
private Component component;
public Decorator(Component component){
this.component = component;
}
@Override
public void doSomething(){
component.doSomething();
}
}
public class ConcreteDecorator1 extends Decorator{
public ConcreteDecorator1(Component component){
super(component);
}
@Override
public void doSomething(){
super.doSomething();
this.doAnotherThing();
}
private void doAnotherThing(){
System.out.println("功能B");
}
}
public class ConcreteDecorator2 extends Decorator{
public ConcreteDecorator2(Component component){
super(component);
}
@Override
public void doSomething(){
super.doSomething();
this.doAnotherThing();
}
private void doAnotherThing(){
System.out.println("功能C");
}
}
public class Client {
public static void main(String[] args) {
// 节点流
Component component = new ConcreteComponent();
// 过滤流
Component component2 = new ConcreteDecorator1(component);
component2.doSomething();
System.out.println("------------");
// 过滤流
Component component3 = new ConcreteDecorator2(component2);
component3.doSomething();
System.out.println("------------");
Component component11 = new ConcreteDecorator1(new ConcreteDecorator2(new ConcreteComponent()));
component11.doSomething();
}
}