设计模式--装饰器模式

    技术2026-02-26  4

    简介

    装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

    装饰器模式中的角色有: 抽象构件(Component)角色:给出一个抽象接口,已规范准备接收附加责任的对象。

    public interface Component { public void sampleOpreation(); }

    具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类

    public class ConcreteComponent implements Component { @Override public void sampleOpreation() { // TODO 完成相关的业务代码 } }

    装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

    public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } @Override public void sampleOpreation() { //委派给构件 component.sampleOpreation(); } }

    具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。

    public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } @Override public void sampleOpreation() { super.sampleOpreation(); //TODO 完成相关的业务代码 } }

    装饰器模式的类图如下:

    示例

    仍然以打印机为例,添加3D打印 1.抽象构件(Component)角色

    public interface Printer { void print(); }

    2.具体构件(ConcreteComponent)角色

    public class PaperPrinter implements Printer { @Override public void print() { System.out.println("Paper Printer"); } } public class PlasticPrinter implements Printer { @Override public void print() { System.out.println("Plastic Printer"); } }

    3.装饰(Decorator)角色

    public class PrinterDecorator implements Printer { private Printer printer; public PrinterDecorator(Printer printer) { this.printer = printer; } @Override public void print() { printer.print(); } }

    4.具体装饰(ConcreteDecorator)角色

    public class Printer3D extends PrinterDecorator { public Printer3D(Printer printer) { super(printer); } @Override public void print() { System.out.println("3D"); super.print(); } }

    5.Main验证

    public class DecoratorMain { public static void main(String[] args) { Printer plasticPrinter = new PlasticPrinter(); Printer plastic3DPrinter = new Printer3D(new PlasticPrinter()); Printer paper3DPrinter = new Printer3D(new PaperPrinter()); plasticPrinter.print(); plastic3DPrinter.print(); paper3DPrinter.print(); } }
    Processed: 0.009, SQL: 10