* 装饰者模式解析 * 应用场景: * 拓展一个类的功能或者给一个类添加附属指责 * 优点: * 1.不改变原有类的功能情况下给一个类拓展功能 * 2.使用不同的组合可以实现不同的效果 * 3.符合开闭原则 * 经典案例: * javax.servlet.http.HttpServletRequestWrapper * HttpServletRequestWrapper的使用可参照博客: * https://blog.csdn.net/qll19970326/article/details/80793465
以下为一个汽车实际例子:
装饰者:一辆更快的汽车(FastCarDecorator),一辆更舒适的汽车(ComfortableDecorator)
被装饰者:汽车(CarComponent)
package com.cc.xlz.designmodel.Decorator;
/**
* 装饰者模式测试类
* 应用场景:
* 拓展一个类的功能或者给一个类添加附属指责
* 优点:
* 1.不改变原有类的功能情况下给一个类拓展功能
* 2.使用不同的组合可以实现不同的效果
* 3.符合开闭原则
* 经典案例:
* javax.servlet.http.HttpServletRequestWrapper
* 使用可参照博客:
* https://blog.csdn.net/qll19970326/article/details/80793465
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
public class DecoratorTest {
public static void main(String[] args) {
/*
* 一辆速度更快的车
* @author xionglz
* @date 2022-02-26
* @param args
* @return void
**/
Component component = new FastCarDecorator(new CarComponent());
component.operate();
System.out.println("----------------------分割线----------------------");
/*
* 一辆速度更快且舒适的车
* @author xionglz
* @date 2022-02-26
* @param args
* @return void
**/
Component component1 = new ComfortableCarDecorator(component);
component1.operate();
}
}
/**
* 模拟被装饰者
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
interface Component{
/**
* 定义行为方法
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
void operate();
}
/**
* 模拟具体被装饰者行为类(以汽车为例)
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
class CarComponent implements Component{
@Override
public void operate() {
System.out.println("我是一台汽车.");
}
}
/**
* 定义装饰器
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
abstract class Decorator implements Component{
Component component;
/**
* 定义一个接收“被装饰者”的构造函数
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
public Decorator(Component component){
this.component = component;
}
}
/**
* 定义具体装饰者
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
class FastCarDecorator extends Decorator{
/**
* 定义一个接收“被装饰者”的构造函数
*
* @param component
* @return
* @author xionglz
* @date 2022-02-26
**/
public FastCarDecorator(Component component) {
super(component);
}
@Override
public void operate() {
component.operate();
System.out.println("我拥有更快的速度,零百加速6秒");
}
}
/**
* 定义具体装饰者
* @author xionglz
* @date 2022-02-26
* @param
* @return
**/
class ComfortableCarDecorator extends Decorator{
/**
* 定义一个接收“被装饰者”的构造函数
*
* @param component
* @return
* @author xionglz
* @date 2022-02-26
**/
public ComfortableCarDecorator(Component component) {
super(component);
}
@Override
public void operate() {
component.operate();
System.out.println("我拥有更舒服的驾驶体验,座椅通风,八向调节");
}
}