定义:装饰(Decorator)模式又叫包装模式。允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替代方案。
意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
何时使用:在不想增加很多子类的情况下扩展类。
优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
步骤 1
创建一个接口:
/*汽车基类*/
public interface Car {
public void run();
public void sendSomething();
}
步骤 2
创建实现接口的实体类。
/*小轿车*/
public class Sedan implements Car{
public void run() {
System.out.println("小轿车在跑");
}
public void sendSomething() {
System.out.println("小轿车运送东西");
}
}
/*大卡车*/
public class Truck implements Car{
public void run() {
System.out.println("大卡车在跑");
}
public void sendSomething() {
System.out.println("大卡车在运送东西");
}
}
步骤 3
创建实现了 Car接口的抽象装饰类。
/*创建实现了 Car 接口的抽象装饰类。
*/
public class CarDecorator implements Car{
protected Car decoratorcar;
public CarDecorator(Car decoratorcar) {
super();
this.decoratorcar = decoratorcar;
}
public void run() {
decoratorcar.run();
}
public void sendSomething() {
decoratorcar.sendSomething();
}
}
步骤 4
创建扩展了 CarDecorator类的实体装饰类。
/*高铁
* 创建扩展了 CarDecorator 类的实体装饰类。
* */
public class HighSpeedRailCarDecorator extends CarDecorator{
public HighSpeedRailCarDecorator(Car decoratorcar) {
super(decoratorcar);
}
public void run() {
super.run();
decoratorcar.run();
decoratorcar.sendSomething();
setHighSpeedRail(decoratorcar);
}
private void setHighSpeedRail(Car decoratorcar) {
System.out.println("高铁在运行");
}
}
步骤 5
使用 DecoratorPatternDemo来装饰 Car对象。
public class DecoratorPatternDemo {
public static void main(String[] args) {
Car sedan=new Sedan();
Car highspeedrail=new HighSpeedRailCarDecorator(sedan);
highspeedrail.run();
System.out.println();
Car truck=new Truck();
Car highspeedrail1=new HighSpeedRailCarDecorator(truck);
highspeedrail1.run();
}
}
步骤 6
执行程序,输出结果:
小轿车在跑
小轿车在跑
小轿车运送东西
高铁在运行
大卡车在跑
大卡车在跑
大卡车在运送东西
高铁在运行