设为首页 加入收藏

TOP

装饰器模式:让你的对象变得更强大(二)
2023-09-09 10:25:50 】 浏览:56
Tags:强大
饰器对象,包装圆形对象 Shape redCircle = new RedShapeDecorator(circle); //创建一个绿色装饰器对象,包装矩形对象 Shape greenRectangle = new GreenShapeDecorator(rectangle); //调用各个对象的方法,展示不同的效果 System.out.println("Normal circle:"); circle.draw(); System.out.println("Normal rectangle:"); rectangle.draw(); System.out.println("Red circle:"); redCircle.draw(); System.out.println("Green rectangle:"); greenRectangle.draw(); } }

输出结果如下:

Normal circle:
Drawing a circle
Normal rectangle:
Drawing a rectangle
Red circle:
Drawing a circle
Setting red border
Green rectangle:
Drawing a rectangle
Setting green border

Spring 代码示例

要想再 Spring 项目中应用装饰器模式,只需对以上代码进行简单改造即可,

  1. 给具体组件类 Circle、Rectangle 添加 @Component 注解,
@Component
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

@Component
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}
  1. 给具体装饰器类 RedShapeDecorator 和 GreenShapeDecorator 类添加 @Component 注解,
@Component
public class GreenShapeDecorator extends ShapeDecorator {
    // 构造方法
    public GreenShapeDecorator(@Qualifier("rectangle") Shape shape) {
        super(shape);
    }

    // 重写draw方法,在调用被包装对象的方法之前或之后添加新的功能
    @Override
    public void draw() {
        // 调用被包装对象的方法
        super.draw();
        // 添加新的功能
        setGreenBorder();
    }

    // 定义新的功能方法
    private void setGreenBorder() {
        System.out.println("Setting green border");
    }
}

@Component
public class RedShapeDecorator extends ShapeDecorator {
    // 构造方法
    public RedShapeDecorator(@Qualifier("circle") Shape shape) {
        super(shape);
    }

    // 重写draw方法,在调用被包装对象的方法之前或之后添加新的功能
    @Override
    public void draw() {
        // 调用被包装对象的方法
        super.draw();
        // 添加新的功能
        setRedBorder();
    }

    // 定义新的功能方法
    private void setRedBorder() {
        System.out.println("Setting red border");
    }
}
  1. 编写 Spring 项目测试代码,
@SpringBootTest
@RunWith(SpringRunner.class)
public class DecoratorTest {

    // 从Spring容器中获取Context对象
    @Autowired
    private RedShapeDecorator redCircle;
    @Autowired
    private GreenShapeDecorator greenRectangle;

    @Test
    public void test() {
        System.out.println("Red circle:");
        redCircle.draw();
        System.out.println("Green rectangle:");
        greenRectangle.draw();
    }
}

输出结果如下:

Red circle:
Drawing a circle
Setting red border
Green rectangle:
Drawing a rectangle
Setting green border

总结

装饰器模式可以将不同功能的单个模块规划至不同的装饰器类中,各装饰器类独立自主,各司其职。客户端可以根据自己的需求自由搭配各种装饰器,每加一层装饰就会有新的特性体现出来,巧妙的设计让功能模块层层叠加,装饰之上套装饰,最终使原始对象的特性动态地得到增强。

关注公众号【waynblog】每周分享技术干货、开源项目、实战经验、国外优质文章翻译等,您的关注将是我的更新动力!

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇java~掩码的应用 下一篇短信发送+实现高并发下高可用(HT..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目