当前位置: 首页 > news >正文

装饰器模式详解和实现(设计模式 二)

装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许你动态地将对象添加到现有对象中,以提供额外的功能,同时又不影响其他对象。

实现示例

1.定义一个接口或抽象类,表示被装饰对象的公共接口

//抽象类组件类
public interface Component {void operation();
}

2、创建一个具体的实现类,实现该接口(也就是初始功能的类)

//具体组件类
public class ConcreteComponent implements Component {@Overridepublic void operation() {System.out.println("执行原始操作");//原始功能}
}

3、创建一个装饰器类,实现与被装饰对象相同的接口,并持有一个对被装饰对象的引用

//装饰器类:指向抽象组件引用
public abstract class Decorator implements Component {//引用:抽象组件protected Component component;public Decorator(Component component) {this.component = component;}@Overridepublic void operation() {component.operation();//原始功能}
}

4、创建具体的装饰器类,通过在装饰器类中添加额外的功能来扩展被装饰对象的行为(添加新功能)

//具体装饰器类A
public class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) {super(component);}@Overridepublic void operation() {super.operation();//原始功能System.out.println("添加额外功能A");}
}
//具体装饰器类B
public class ConcreteDecoratorB extends Decorator {public ConcreteDecoratorB(Component component) {super(component);}@Overridepublic void operation() {super.operation();System.out.println("添加额外功能B");}
}

5、使用新功能(既能使用使用原始功能、也能使用新功能)

public class Main {public static void main(String[] args) {Component component=new ConcreteComponent();//执行原始操作component.operation();System.out.println("--------------------------");//执行额外操作A(包含原始操作)Component componentA=new ConcreteDecoratorA(new ConcreteComponent());componentA.operation();System.out.println("--------------------------");//同时执行额外操作A和B(嵌套)Component componentB=new ConcreteDecoratorB(new ConcreteDecoratorA(new ConcreteComponent()));componentB.operation();}
}

输出结果展示
在这里插入图片描述

http://www.lryc.cn/news/179440.html

相关文章:

  • 面试问到MySQL模块划分与架构体系怎么办
  • 并查集及其优化
  • LeetCode 周赛上分之旅 #48 一道简单的树上动态规划问题
  • mysql报错:Column Count Doesn‘t Match Value Count at Row 1
  • 安卓 kuaishou 设备did和egid 学习分析
  • 基于Vue+ELement实现增删改查案例与表单验证(附源码)
  • webpack:使用externals配置来排除打包后的某个依赖插件IgnorePlugin的使用
  • 2023年中国工业脱水机行业供需分析:随着自动化和智能化技术的快速发展,销量同比增长4.9%[图]
  • [论文笔记]MacBERT
  • AI发展目前最大挑战是什么?
  • 自然语言处理NLP:LTP、SnowNLP、HanLP 常用NLP工具和库对比
  • 百度交易中台之内容分润结算系统架构浅析
  • 【索引】常见的索引、B+树结构、什么时候需要使用索引、优化索引方法、索引主要的数据结构、聚簇索引、二级索引、创建合适的索引等重点知识汇总
  • Egg 封装接口返回信息
  • Android AMS——创建APP进程(五)
  • 凉鞋的 Unity 笔记 102. 场景层次 与 GameObject 的增删改查
  • 信息安全:网络安全审计技术原理与应用.
  • 嵌入式Linux应用开发-第十三章APP怎么读取按键值
  • Web 中间件怎么玩?
  • HMTL知识点系列(4)
  • CFS内网穿透靶场实战
  • 【RabbitMQ实战】07 3分钟部署一个RabbitMQ集群
  • PS 切片工具 选择切片 切片存储
  • Git版本控制系统
  • Element UI搭建首页导航和左侧菜单以及Mock.js和(组件通信)总线的运用
  • What is an HTTP Flood DDoS attack?
  • 第 114 场 LeetCode 双周赛题解
  • [Java框架] Java常用爬虫框架推荐
  • Kafka:安装与简单使用
  • 029-从零搭建微服务-消息队列(一)