2021年9月22日-设计模式之装饰者模式

第九章:装饰者模式

一、问题引入

现在是这么个情况:有这么几个机器人,这几个机器人分别会安装主机、安装显示器、装系统。现在我想要一个既能安装主机、又能安装显示器的机器人。如果用继承的方式新建一个类是可以完成要求的,但是如果后续又需要一个既能安装显示器又能装系统的机器人的话又要新建一个类。随着我们的需求增加,类的数量会越来越多。

所以针对这个问题,我们选择装饰者模式。装饰者模式又称包装模式(Wrapper Pattern),属于结构型设计模式。该模式可以让一个对象动态的增加新功能(代理模式???)

二、装饰者模式

一般的结构类图:

在这里插入图片描述

  • 抽象组件(Component)
  • 抽象装饰者(Decorator)
  • 具体组件(ConcreteComponent)
  • 具体装饰者(ConcreteDecoratorA)

三、装饰者实例

在这里插入图片描述

这里的 Robot 就是抽象组件,RobotDecorate 就是抽象装饰者,HostRobot 就是具体组件,ScreenRobot 和 SystemRobot 就是具体装饰者

Robot 接口

public interface Robot {
    void operate();
}

HostRobot 类

public class HostRobot implements Robot {
    @Override
    public void operate() {
        System.out.println("安装主机中。。。");
    }
}

RobotDecorate 类

public abstract class RobotDecorator implements Robot{
    protected Robot robot;
}

ScreenRobot 类

public class ScreenRobot extends RobotDecorator {
    public ScreenRobot(Robot robot) {
        this.robot = robot;
    }

    @Override
    public void operate() {
        this.robot.operate();
        System.out.println("安装屏幕中。。。");
    }
}

SystemRobot 类

public class SystemRobot extends RobotDecorator {
    public SystemRobot(Robot robot) {
        this.robot = robot;
    }

    @Override
    public void operate() {
        robot.operate();
        System.out.println("安装系统中。。。");
    }
}

测试类

public class DecoratorTest {
    public static void main(String[] args) {
        ScreenRobot screenRobot = new ScreenRobot(new HostRobot());
        SystemRobot systemRobot = new SystemRobot(screenRobot);
        
        // systemRobot 现在就具有了所有能力
        systemRobot.operate();
    }
}

四、模式总结

装饰者模式总的来所就是在不新设计一个类的情况下就可以扩展一个类的功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值