装饰模式:动态地给一个对象添加一些额外的职责。
就增加功能来说,装饰模式相比生成子类更为灵活。
public interface Person {
void eat();
}
public class Man implements Person{
@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println("男人在吃饭。。。");
}
}
public abstract class Decorator implements Person{
protected Person person;
public void setPerson(Person person){
this.person = person;
}
public void eat(){
person.eat();
}
}
public class ManDecoratorA extends Decorator {
public void eat(){
super.eat();
reEat();
System.out.println("ManDecoratorA");
}
private void reEat() {
// TODO 自动生成的方法存根
System.out.println("再吃一顿。。。");
}
}
public class ManDecoratorB extends Decorator {
public void eat(){
super.eat();
System.out.println("========");
System.out.println("ManDecoratorB");
}
}
public class Test {
public static void main(String[] args) {
Man man = new Man();
ManDecoratorA man1 = new ManDecoratorA();
ManDecoratorB man2 = new ManDecoratorB();
//装饰过程
man1.setPerson(man);
man2.setPerson(man1);
man2.eat();
}
}
》》例程:
1,Person—— 定义一个对象接口,可以给对象动态添加功能。
2,Man——Person的实现类,就是给此类型的对象添加功能。
3,Decorator——维持一个指向Person对象的指针,并定义一个与Person接口一致的接口。
4,ManDecoratorA、ManDecoratorB——负责向Man对象添加功能。
》》适用场景:
1,在不影响其他对象的情况下,动态地给单个对象添加功能。
2,当不能采用子类的方法进行扩充时。
》》小结:
装饰模式是为已有功能动态地添加更多功能的一种方式。
它把每个要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。
因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择的、按顺序地使用装饰功能包装对象了。