概念:动态的为对象增加额外的职责,比生成子类更为灵活。
实例中,Component ConcreteComponent都为Person。
//公共接口,也是目标类,职责的承受者
public interface Person {
void eat();
}
//装饰者类,负责生成职责
public abstract class Decorator implements Person {
protected Person person;
public void setPerson(Person person) {
this.person = person;
}
public void eat() {
person.eat();
}
}
//具体职责A
public class ManDecoratorA extends Decorator {
public void eat() {
super.eat();
reEat();
System.out.println("ManDecoratorA类");
}
public void reEat() {
System.out.println("再吃一顿饭");
}
}
//具体职责B
class ManDecoratorB extends Decorator {
public void eat() {
super.eat();
System.out.println("吃成猪");
System.out.println("ManDecoratorB类");
}
}
//具体职责C
class ManDecoratorC extends Decorator {
public void eat() {
super.eat();
System.out.println("吃前祈祷");
System.out.println("ManDecoratorC类");
}
//调用
public static void main(String[] args) {
Man man = new Man();
ManDecoratorC md3 = new ManDecoratorC();
ManDecoratorA md1 = new ManDecoratorA();
ManDecoratorB md2 = new ManDecoratorB();
//先设置父类中 Person 的具体实现 ,在执行eat方法时。 super.eat();都是先执行父类的eat(),也就是
//具体传入的实现,
/**
* 执行第一条前,父类中 Person为Man,父类执行的eat()就是Man的eat()
*/
md3.setPerson(man);
/**
* 执行第二条前,父类中 Person为Man3,父类执行的eat()就是Man3的eat()
*/
md1.setPerson(md3);
/**
* 执行第三条前,父类中 Person为Man1,父类执行的eat()就是Man1的eat()
*/
md2.setPerson(md1);
/**
* 执行第四条前,先执行父类的eat(),在执行本类。md2的父类eat()为eat1(),md1的父类eat()为eat3(),
* ,md3的父类eat()为具体实现的eat()
*/
md2.eat();
}