概念与介绍
定义
指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,装饰器模式属于对象结构型模式。
应用场景
通常,我们会使用继承来扩展一个类,但继承会让类引入静态特征。如果扩展的功能较多,子类会很膨胀。在这种情况下可以考虑使用装饰器模式,对于扩展功能这点来说,它比生成子类更加灵活。
应用举例
1.吃煎饼果子时可以加鸡蛋、香肠等,但不管加不加,都不会改变它是煎饼果子这一事实。
2.机器人可以选择给自己加装火箭炮、喷气背包等等(注意只能是加装配件,不能是改装,因为装饰器模式是指不改变当前对象结构的情况)。
主要优点
1.装饰器是继承的有力补充,比继承灵活,在不改变原有对象的情况下,动态的给一个对象扩展功能,即插即用。
2.装饰类和被装饰类可以独立发展,两者不会耦合。
主要缺点
过度使用时,会让程序变的很复杂。
结构与实现
模式的结构
模式的实现
//抽象构件角色
interface Component {
public void operation();
}
//具体构件角色——战争机器人
class Robot implements Component {
public Robot() {
System.out.println("创建机器人");
}
public void operation() {
System.out.println("进入战斗状态:");
}
}
//抽象装饰角色
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
//具体装饰1——火箭炮
public class Rockets extends Decorator {
public Rockets(Component component) {
super(component);
}
public void operation() {
super.operation();
addedRockets();
}
public void addedRockets() {
System.out.println("已加装火箭炮,随时准备发射!");
}
}
//具体装饰2——喷气背包
public class JetPack extends Decorator {
public JetPack(Component component) {
super(component);
}
public void operation() {
super.operation();
addedJetpack();
}
public void addedJetpack() {
System.out.println("已加装喷气背包,随时可以撤离!");
}
}
//装饰器模式
public class DecoratorPattern {
public static void main(String[] args) {
Component robot = new Robot();
System.out.println("------------加装前-------------");
robot.operation();
System.out.println("------------加装后-------------");
//加装火箭炮
Component rockets = new Rockets(robot);
rockets.operation();
//加装喷气背包
Component jetPack = new JetPack(robot);
jetPack.operation();
}
}
程序运行结果
创建机器人
------------加装前-------------
进入战斗状态:
------------加装后-------------
进入战斗状态:
已加装火箭炮,随时准备发射!
进入战斗状态:
已加装喷气背包,随时可以撤离!