概述:動態地給一個對象添加一些額外的職責或者行爲
角色:
- 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();
}
打印:
我是男人,我在吃飯
我的度量大,我還得再吃一頓