类图
package cn.装饰模式;
public class Component { //抽象构件
public void operation() {
System.out.println("抽象构件类operation()方法");
}
}
package cn.装饰模式;
public class ConcreteComponent extends Component{ //具体构件
public void operation() {
System.out.println("具体构件类的operation()方法");
}
}
package cn.装饰模式;
public class Decorator extends Component{ //抽象装饰类
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
package cn.装饰模式;
public class ConcreteDecoratorA extends Decorator{ //具体装饰类A
public ConcreteDecoratorA(Component component) {
super(component);
}
public void operation() {
super.operation();
addedBehavior();
}
public void addedBehavior() {
//新增方法
System.out.println("新增方法A");
}
}
package cn.装饰模式;
public class ConcreteDecoratorB extends Decorator{ //具体装饰类B
public ConcreteDecoratorB(Component component) {
super(component);
}
public void operation() {
super.operation();
addedBehavior();
}
public void addedBehavior() {
//新增方法
System.out.println("新增方法B");
}
}
package cn.装饰模式;
/*
* 假如Component是变形金刚类,CocreteComponent是车类,ComcreteComponentA是机器人类,
* ComcreteComponentB是飞机类。那么对象component是车,componentA是机器人,componentB
* 是飞机,componentAB是机器人飞机,componentBA是飞机机器人。每个对象都是在车的基础上
* 进行修饰的。这其实就是透明模式,只有当ComcreteComponentA和ComcreteComponentB中
* 的operation()方法一致时才可以使用。否则就是半透明模式。
*/
public class Client { //客户端类
public static void main(String[] args) {
Component component, componentA,componentB,componentAB,componentBA;
component = new ConcreteComponent();
component.operation();
System.out.println("-----------------------");
componentA = new ConcreteDecoratorA(component);
componentA.operation();
System.out.println("-----------------------");
componentB = new ConcreteDecoratorB(component);
componentB.operation();
System.out.println("-----------------------");
componentAB = new ConcreteDecoratorB(componentA);
componentAB.operation();
System.out.println("-----------------------");
componentBA = new ConcreteDecoratorA(componentB);
componentBA.operation();
System.out.println("-----------------------");
}
}
运行效果图