【设计模式】—— 装饰模式Decorator

  前言:【模式总览】——————————by xingoo

  模式意图

  在不改变原来类的情况下,进行扩展。

  动态的给对象增加一个业务功能,就功能来说,比生成子类更方便。

  应用场景

  1 在不生成子类的情况下,为对象动态的添加某些操作。

  2 处理一些可以撤销的职责。

  3 当不能使用生成子类来扩充时。

  模式结构

 

  Component 外部接口,用于定义外部调用的形式。提供默认的处理方法。

interface Component{
     public void operation();
 }

 

  ConcreteComponent  具体的处理类,用于实现operation方法。

复制代码
class ConcreteComponent implements Component{

    @Override
    public void operation() {
        // TODO Auto-generated method stub
        System.out.println("ConcreteComponent operation()");
    }
    
}
复制代码

  Decorator 装饰类,内部关联一个component对象,调用其operation方法,并添加自己的业务操作。

复制代码
class Decorator implements Component{
    private Component component;
    @Override
    public void operation() {
        // TODO Auto-generated method stub
        System.out.println("before decorator!");
        component.operation();
        System.out.println("after decorator!");
    }
    public Decorator() {
        // TODO Auto-generated constructor stub
    }
    public Decorator(Component component){
        this.component = component;
    }
    
}
复制代码

  全部代码

复制代码
 1 package com.xingoo.decorator;
 2 interface Component{
 3     public void operation();
 4 }
 5 class ConcreteComponent implements Component{
 6 
 7     @Override
 8     public void operation() {
 9         // TODO Auto-generated method stub
10         System.out.println("ConcreteComponent operation()");
11     }
12     
13 }
14 class Decorator implements Component{
15     private Component component;
16     @Override
17     public void operation() {
18         // TODO Auto-generated method stub
19         System.out.println("before decorator!");
20         component.operation();
21         System.out.println("after decorator!");
22     }
23     public Decorator() {
24         // TODO Auto-generated constructor stub
25     }
26     public Decorator(Component component){
27         this.component = component;
28     }
29     
30 }
31 
32 
33 public class test {
34     public static void main(String[] args) {
35         Component component = new Decorator(new ConcreteComponent());
36         component.operation();
37     }
38 }
复制代码

  运行结果

before decorator!
ConcreteComponent operation()
after decorator!

 

posted @   xingoo  阅读(1041)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2013-10-30 关于cuda拷贝的速度测试
2012-10-30 用vc++做滚动条控件
点击右上角即可分享
微信分享提示