概述:动态地给一个对象添加一些额外的职责或者行为
角色:
- Component 定义一个对象接口,可以给这些对象动态地添加职责
- ConcreteComponent 定义一个对象,可以给这个对象添加一些职责
- Decorator 维持一个指向Component对象的指针,并定义一个与Component接口一致的接口
- ConcreteDecorator 向组件添加职责
类图:
实现:
人类接口:
interface People {
void eat();
}
男人对象,实现人类接口
public class Man implements People {
public void eat() {
System.out.println("我是男人,我在吃饭");
}
}
装饰抽象类:
public abstract class Decorator implements People{
protected People people;
public void setPeople(People people){
this.people = people;
}
public void eat(){
people.eat();
}
}
装饰具体实现类,添加了再吃一顿的行为:
public class ConDecorator extends Decorator {
public void eat(){
super.eat();
eatAgain();
}
public void eatAgain(){
System.out.println("我的度量大,我还得再吃一顿");
}
}
测试:
public static void main(String[] args) {
Decorator decorator = new ConDecorator();
People people = new Man();
decorator.setPeople(people);
decorator.eat();
}
打印:
我是男人,我在吃饭
我的度量大,我还得再吃一顿