动态地为一个对象增加新的功能。无需通过继承增加子类就能扩展对象的新功能,使用对象的关联代替继承。常用场景:IO中输入流和输出流的设计。
主要包含以下角色:
Component抽象构件角色
ConcreteComponent具体构建角色
Decorator装饰角色
ConcreteDecorator具体装饰角色
下面有一个场景:抽象构件就是一个汽车接口,具体构建就是一个陆地上跑的普通车,装饰角色就是实现了汽车接口,但是持有普通车的一个实例,具体装饰角色就是继承了装饰角色类,增加了新的功能。
//抽象构件角色
public interface Car {
void move();
}
//具体构建角色
class CommonCar implements Car{
@Override
public void move() {
System.out.println("陆地上跑");
}
}
//装饰角色
class SpecialCar implements Car{
protected Car car;
public SpecialCar(Car car) {
this.car = car;
}
@Override
public void move() {
car.move();
}
}
//具体装饰角色
class FlyCar extends SpecialCar{
public FlyCar(Car car) {
super(car);
}
public void fly(){
System.out.println("天上飞");
}
public void move(){
super.move();
fly();
}
}
//具体装饰角色
class WaterCar extends SpecialCar{
public WaterCar(Car car) {
super(car);
}
public void swim(){
System.out.println("水上游");
}
public void move(){
super.move();
swim();
}
}
//具体装饰角色
class AICar extends SpecialCar{
public AICar(Car car) {
super(car);
}
public void auto(){
System.out.println("自动驾驶");
}
public void move(){
super.move();
auto();
}
}
测试类
public class Test {
public static void main(String[] args) {
CommonCar commonCar = new CommonCar();
commonCar.move();
System.out.println("增加新的功能:飞行-----");
FlyCar flyCar = new FlyCar(commonCar);
flyCar.move();
System.out.println("构造全能的汽车-----");
//这里就很像io流里面的new BufferedInputStream(new(new()....))
AICar aiCar = new AICar(new WaterCar(new FlyCar(new CommonCar())));
aiCar.move();
}
}
最后的输出结果:
陆地上跑
增加新的功能:飞行—–
陆地上跑
天上飞
构造全能的汽车—–
陆地上跑
天上飞
水上游
自动驾驶