设计模式--装饰器模式

简介

装饰器模式(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();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值