【kotlin】利用by关键字更加方便地实现装饰器模式

devtools/2024/9/20 3:59:30/ 标签: kotlin, 装饰器模式, 开发语言, 设计模式

  关于kotlin中的by关键字的用法,kotlin官方文档属性委托这一节讲得很清楚。

  简单来说就是这样的,假设存在一个接口Component如下:

kotlin">interface Component {fun method1(): IntArrayfun method2(a: Int)fun method3(a: Int, str: String)
}

  那么对于实现该接口的方法,可以这样:

kotlin">class Decorator(private val component: Component): Component {override fun method1(): IntArray = component.method1()override fun method2(a: Int) = component.method2(a)override fun method3(a: Int, str: String) = component.method3(a, str)
}

  但也可以通过by关键字更简单地实现:

kotlin">class Decorator(private val component: Component): Component by component

  这两段代码功能一致。

  于是我们便能利用这一功能来更方便地实现装饰器模式,现在我们来实现三个装饰器类,分别对Component的三个方法进行装饰。

kotlin">interface Component {fun method1(): IntArrayfun method2(a: Int)fun method3(a: Int, str: String)
}class Decorator1(private val component: Component,private inline val f0: ()->Unit = {},private inline val f1: (arr: IntArray)->IntArray = {arr -> arr}
): Component by component {override fun method1(): IntArray {f0()return f1(component.method1())}
//	相当于自动实现了
//	override fun method2(a: Int) = component.method2(a)
//	override fun method3(a: Int, str: String) = component.method3(a, str)
}class Decorator2(private val component: Component,private inline val f0: (Int)->Unit = {},private inline val f1: (Int)->Unit = {}
): Component by component {override fun method2(a: Int) {f0(a)component.method2(a)f1(a)}
//	override fun method1(): IntArray = component.method1()
//	override fun method3(a: Int, str: String) = component.method3(a, str)
}class Decorator3(private val component: Component,private inline val f0: (Int, String)->Unit = {_, _ -> },private inline val f1: (Int, String)->Unit = {_, _ -> }
): Component by component {override fun method3(a: Int, str: String) {f0(a, str)component.method3(a, str)f1(a, str)}
//	override fun method1(): IntArray = component.method1()
//	override fun method2(a: Int) = component.method2(a)
}

  在主函数中调用这三个装饰器。

kotlin">fun main() {val obj1 = object: Component{override fun method1(): IntArray = IntArray(5){it * it}override fun method2(a: Int) = println("a^2 is ${a * a}")override fun method3(a: Int, str: String) = println("a is a, and str is \"$str\"")}val obj2 = object: Component{override fun method1(): IntArray = IntArray(10){it}override fun method2(a: Int) = println("a - 3 is ${a - 3}")override fun method3(a: Int, str: String) = println("say \"$str\" to number a = $a")}val dcrt1: Component = Decorator1(obj1, {}){ arr ->println("old arr is ${arr.contentToString()}")return@Decorator1 IntArray(10) {it * it *it}}val dcrt2: Component = Decorator2(obj1){ a ->println("a is $a")}val dcrt3: Component = Decorator3(obj2, { a, str ->println("say \"$str\" to java $a times")}, {a, str ->println("and say \"$str\" to kotlin $a times")})val dcrt4: Component = Decorator2(Decorator3(obj2){ a, str ->println("say \"$str\" to jetBrains $a times")}){a ->println("a + 3 is ${a + 3}")}display(dcrt1, 10, "Hello world!")display(dcrt2, 15, "Hello kotlin!")display(dcrt3, 20, "Hello, java!")display(dcrt4, 25, "Hello, jetBrains!")}fun display(component: Component, a: Int, str: String) {with(component) {println("--------------------------------")println(method1().contentToString())method2(a)method3(a, str)println("--------------------------------")println()}
}

  运行结果:
运行结果


http://www.ppmy.cn/devtools/16689.html

相关文章

Kotlin语法入门-密封类和密封接口(11)

Kotlin语法入门-密封类和密封接口(11) 文章目录 Kotlin语法入门-密封类和密封接口(11)十一、密封类和密封接口1、密封类2、密封接口 十一、密封类和密封接口 1、密封类 在Kotlin中,密封类(Sealed Class)是一种特殊的类,用于表示受…

Linux fdformat命令教程:如何进行软盘的低级格式化(附案例详解和注意事项)

Linux fdformat命令介绍 fdformat是一个用于对软盘进行低级格式化的命令。这个命令通常用于对软盘进行底层的格式化操作,以便于在软盘上创建新的文件系统。 Linux fdformat命令适用的Linux版本 fdformat命令在大多数Linux发行版中都可以使用,包括但不…

NXP应用随记(七):S32K3XX复位与启动阅读记录

目录 1、复位过程 1.1、概述 1.2、复位产生模块 1.2.1、上电复位 1.2.2、破坏性复位 1.2.3、功能复位 1.3、芯片复位及引导概述 1.4、重置和启动流程图 1.5、复位块序列 2、上电复位 3、破坏性复位 4、功能复位 5、设备配置格式(DCF) 6、重置专题 6.1、重置引脚行…

怎么选合适的图纸加密软件?迅软DSE加密软件功能、安全与易用性并存

利用加密软件进行图纸加密,确保企业的图纸信息能够得到有效保护,防止非法访问和数据泄露。 一、挑选图纸加密软件的注意事项? 用户反馈:参考其他用户的反馈和评价,了解软件在实际使用中的表现和潜在问题。兼容性&…

《A Discriminative Feature Learning Approach for Deep Face Recognition》阅读笔记

论文标题 《A Discriminative Feature Learning Approach for Deep Face Recognition》 一种用于深度人脸识别的判别性特征学习方法 作者 Yandong Wen、Kaipeng Zhang、Zhifeng Li 和 Yu Qiao 来自深圳市计算机视觉与专利重点实验室、中国科学院深圳先进技术研究院和香港中…

牛客NC199 字符串解码【中等 递归,栈的思想 C++/Java/Go/PHP】

题目 题目链接: https://www.nowcoder.com/practice/4e008fd863bb4681b54fb438bb859b92 相同题目: https://www.lintcode.com/problem/575 思路 解法和基础计算器1,2,3类似,递归参考答案C struct Info {string str;int stopindex;Info(str…

linux 系统文件目录颜色及特殊权限对应的颜色

什么决定文件目录的颜色和背景? 颜色 说明 栗子 权限白色表示普通文件 蓝色表示目录 绿色表示可执行文件 浅蓝色链接文件 黄色表示设备文件 红色 表示压缩文件 红色闪烁表示链接的文件有问题 灰色 表示其它文件 可以用字符表示文件的类型&am…

芯片制造的成本与定价

芯片制造的成本与定价之间存在密切关系,芯片制造商在设定产品价格时会充分考虑制造成本,并结合市场策略、竞争态势、客户接受度等多个因素来制定最终售价。以下是关于芯片制造成本与定价之间相互作用的一些关键点: 1. 成本构成 芯片制造成本主要包括以下几个方面: 设计成本…

信息系统项目管理师0069:数据运维(5信息系统工程—5.2数据工程—5.2.3数据运维)

点击查看专栏目录 文章目录 5.2.3数据运维1.数据存储2.数据备份3.数据容灾4.数据质量评价与控制记忆要点总结5.2.3数据运维 数据开发利用的前提是通过合适的方式将数据保存到存储介质上,并能保证有效的访问,还要通过数据备份和容灾手段,保证数据的高可用性。数据质量管理是在…

AI电销机器人系统源码部署之:freeswitch安装Linux

安装 FreeSWITCH(一个开源的电话交换系统)通常需要一些步骤,以下是在 Linux 系统上安装 FreeSWITCH 的基本指南: 准备工作: 确保你有一个运行 Linux 的服务器,并且有 root 或者具有 sudo 权限的用户。确保服…

一文详解视觉Transformer模型压缩和加速策略(量化/低秩近似/蒸馏/剪枝)

视觉Transformer(ViT)在计算机视觉领域标志性地实现了一次革命,超越了各种任务的最先进模型。然而,它们的实际应用受到高计算和内存需求的限制。本研究通过评估四种主要的模型压缩技术:量化、低秩近似、知识蒸馏和剪枝…

OSPF的协议特性

路由汇总的概念 l 路由汇总( Route Aggregation ),又称路由聚合(Route Summarization),指的是把一组明细路由汇聚成一条汇总路由条目的操作 l 路由汇总能够减少路由条目数量、减小路由表规模&#xff0…

什么是OCR转换?

OCR转换是指将图片或扫描文档中的文字内容转换成电子文本的过程。OCR代表光学字符识别(Optical Character Recognition),是一种通过算法和模型来识别图像或文档中的文字,并将其转换成可编辑、可搜索的文本格式。OCR转换通常包括以…

mysql服务器无法启动问题处理

一台hlr服务器用网关软件登录失败,查找原因,发现网关软件连接服务器的tcp的10002端口失败,超时无应答,导致连接失败。 用户反馈核心网hlr,smc无法登录,putty登录服务器,发现hlr10002端口没有打…

http忽略ssl认证

我们在发请求时,会遇到需要ssl证书验证的报错,针对该错误以及所使用的不同的创建连接的方式,进行ssl证书忽略 忽略SSL证书的流程 简介:需要告诉client使用一个不同的TrustManager。TrustManager是一个检查给定的证书是否有效的类…

【Matlab函数分析】对二维或三维散点数据插值函数scatteredInterpolant

🔗 运行环境:Matlab 🚩 撰写作者:左手の明天 🥇 精选专栏:《python》 🔥 推荐专栏:《算法研究》 #### 防伪水印——左手の明天 #### 💗 大家好🤗&#x1f91…

使用git将本地项目上传到github

大致的流程是:创建本地仓库,把代码传到本地仓库,把本地仓库内容传到远程仓库。还不太完整,逐渐摸索使用吧 1、初始化仓库 git init在本地项目的路径中初始化一个仓库。 2、提交到本地 选择需要上传的文件 git add .提交到本地…

CMake+qt+Visual Studio

#使用qt Creator 创建Cmake 项目,使用Cmake Gui 生成sln 工程,使用Visual Studio 开发 ##使用qt Creator 创建CMake项目 和创建pro工程的步骤一致,只是在选择构建系统的步骤上选择CMake,接下来步骤完全相同 工程新建完成之后,构建cmake 项…

第11章 Android特色开发——基于位置的服务

第11章 Android特色开发——基于位置的服务 本章中,将要学习一些全新的Android技术,这些技术有别于传统的PC或Web领域的应用技术,是只有在移动设备上才能实现的。 基于位置的服务(Location Based Service)。由于移动…

机器学习(三)之监督学习2

前言: 本专栏一直在更新机器学习的内容,欢迎点赞收藏哦! 笔者水平有限,文中掺杂着自己的理解和感悟,如果有错误之处还请指出,可以在评论区一起探讨! 1.支持向量机(Support Vector Ma…