装饰器模式又叫包装模式,通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替代方案。运用装饰器模式最经典的例子就是Java的IO各种流。
角色和职责:
抽象组件角色:一个抽象接口,是被装饰类和装饰类的父接口。
具体组件角色:为抽象组件的实现类。
抽象装饰角色:包含一个组件的引用,并定义了与抽象组件一致的接口。
具体装饰角色:为抽象装饰角色的实现类。负责具体的装饰。
以下就是装饰器模式的一个DEMO:
抽象组件角色:
public interface Car {
public void show();
}
具体组件角色:
public class RunCar implements Car {
@Override
public void show() {
this.run();
}
public void run() {
System.out.println("Run...");
}
}
抽象装饰角色:
public abstract class CarDecorator implements Car {
private Car car;
public CarDecorator(Car car) {
this.car = car;
}
public Car getCar() {
return car;
}
@Override
public abstract void show();
}
具体装饰角色1:
public class FlyCarDecorator extends CarDecorator {
public FlyCarDecorator(Car car) {
super(car);
}
@Override
public void show() {
this.getCar().show();
this.fly();
}
public void fly() {
System.out.println("Fly...");
}
}
具体装饰角色2:
public class SwimCarDecorator extends CarDecorator {
public SwimCarDecorator(Car car) {
super(car);
}
@Override
public void show() {
this.getCar().show();
this.swim();
}
public void swim() {
System.out.println("Swim...");
}
}
客户端调用测试类:
public class ClientApp {
public static void main(String[] args) {
Car car = new RunCar();
car.show();
System.out.println("----------------");
CarDecorator swimCar = new SwimCarDecorator(car);
swimCar.show();
System.out.println("----------------");
CarDecorator flySwimCar = new FlyCarDecorator(swimCar);
flySwimCar.show();
}
}
以上代码虽然没什么实际意义,但是也可以从中了解到装饰器模式的使用方式。