说明:动态的给对象添加一些额外的功能
角色:component(构件) ConcreteComponent(具体构件) Decorator(装饰器) ConcreteDecorator(具体装饰器)
Component
定义一个对象接口,可以给这些对象动态地添加职责。
ConcreteComponent
是定义了一个具体的对象,也可以给这个对象添加一些职责。
Decorator
装饰抽象类,继承了Component,扩展了Component类的功能,对于Component无需知道Decorator。
ConcreteDecorator
具体实现的装饰对象,给Component添加职责的功能。
比如我们有一个机器人,最初的功能只是对话和唱歌,现在我们要添加额外的功能让他能跳舞拖地
首先定义一个机器人接口里面有个dosometing方法,
然后实现这个方法对话唱歌,
再用一个类实现这个方法附加新功能
//需要被装饰的对象 Component
public interface Robot {
void doSometing();
}
//ConcreteComponent
public class OneRobot implements Robot{
@Override
public void doSometing() {
System.out.println("唱歌");
System.out.println("对话");
}
}
//装饰器
public class RobotDecorator implements Robot{
private Robot robot;
public RobotDecorator(Robot robot) {
this.robot = robot;
}
@Override
public void doSometing() {
robot.doSometing();
}
public void doOther(){
System.out.println("拖地");
System.out.println("跳舞");
}
}