第九章:装饰者模式
一、问题引入
现在是这么个情况:有这么几个机器人,这几个机器人分别会安装主机、安装显示器、装系统。现在我想要一个既能安装主机、又能安装显示器的机器人。如果用继承的方式新建一个类是可以完成要求的,但是如果后续又需要一个既能安装显示器又能装系统的机器人的话又要新建一个类。随着我们的需求增加,类的数量会越来越多。
所以针对这个问题,我们选择装饰者模式。装饰者模式又称包装模式(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();
}
}
四、模式总结
装饰者模式总的来所就是在不新设计一个类的情况下就可以扩展一个类的功能