主要的软件设计模式及其在Kotlin中的实现示例

ops/2024/10/18 16:49:07/

软件设计模式(Software Design Patterns)是面向对象设计中常用的解决方案,它们为常见的软件设计问题提供了一些被证明有效的解决方案。以下是一些主要的软件设计模式及其在Kotlin中的实现示例。

创建型模式(Creational Patterns)

单例模式(Singleton Pattern)

确保一个类只有一个实例,并提供全局访问点。

kotlin">object Singleton {init {println("Singleton instance created")}fun doSomething() {println("Doing something")}
}// 使用
fun main() {Singleton.doSomething()
}
工厂模式(Factory Pattern)

定义一个创建对象的接口,但由子类决定要实例化的类。

kotlin">interface Product {fun use()
}class ConcreteProductA : Product {override fun use() {println("Using Product A")}
}class ConcreteProductB : Product {override fun use() {println("Using Product B")}
}class ProductFactory {fun createProduct(type: String): Product {return when (type) {"A" -> ConcreteProductA()"B" -> ConcreteProductB()else -> throw IllegalArgumentException("Unknown product type")}}
}// 使用
fun main() {val factory = ProductFactory()val productA = factory.createProduct("A")productA.use()val productB = factory.createProduct("B")productB.use()
}
抽象工厂模式(Abstract Factory Pattern)

提供一个接口,用于创建相关或依赖对象的家族,而不需要指定具体类。

kotlin">interface Button {fun click()
}class WindowsButton : Button {override fun click() {println("Windows Button clicked")}
}class MacButton : Button {override fun click() {println("Mac Button clicked")}
}interface GUIFactory {fun createButton(): Button
}class WindowsFactory : GUIFactory {override fun createButton(): Button {return WindowsButton()}
}class MacFactory : GUIFactory {override fun createButton(): Button {return MacButton()}
}// 使用
fun main() {val factory: GUIFactory = WindowsFactory()val button = factory.createButton()button.click()
}
建造者模式(Builder Pattern)

将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

kotlin">class Product private constructor(builder: Builder) {val partA: String?val partB: String?val partC: String?init {partA = builder.partApartB = builder.partBpartC = builder.partC}class Builder {var partA: String? = nullprivate setvar partB: String? = nullprivate setvar partC: String? = nullprivate setfun setPartA(partA: String) = apply { this.partA = partA }fun setPartB(partB: String) = apply { this.partB = partB }fun setPartC(partC: String) = apply { this.partC = partC }fun build() = Product(this)}
}// 使用
fun main() {val product = Product.Builder().setPartA("A").setPartB("B").setPartC("C").build()println("Product parts: ${product.partA}, ${product.partB}, ${product.partC}")
}

结构型模式(Structural Patterns)

适配器模式(Adapter Pattern)

将一个类的接口转换成客户希望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以协同工作。

kotlin">interface Target {fun request()
}class Adaptee {fun specificRequest() {println("Specific request")}
}class Adapter(private val adaptee: Adaptee) : Target {override fun request() {adaptee.specificRequest()}
}// 使用
fun main() {val adaptee = Adaptee()val adapter = Adapter(adaptee)adapter.request()
}
装饰器模式(Decorator Pattern)

动态地将责任附加到对象上,提供了一种灵活替代继承的方法来扩展功能。

kotlin">interface Component {fun operation()
}class ConcreteComponent : Component {override fun operation() {println("Concrete Component operation")}
}open class Decorator(private val component: Component) : Component {override fun operation() {component.operation()}
}class ConcreteDecorator(component: Component) : Decorator(component) {override fun operation() {super.operation()addedBehavior()}private fun addedBehavior() {println("Added behavior")}
}// 使用
fun main() {val component: Component = ConcreteDecorator(ConcreteComponent())component.operation()
}
代理模式(Proxy Pattern)

为另一个对象提供一个代理以控制对这个对象的访问。

kotlin">interface Subject {fun request()
}class RealSubject : Subject {override fun request() {println("RealSubject request")}
}class Proxy(private val realSubject: RealSubject) : Subject {override fun request() {println("Proxy request")realSubject.request()}
}// 使用
fun main() {val realSubject = RealSubject()val proxy = Proxy(realSubject)proxy.request()
}
外观模式(Facade Pattern)

为子系统中的一组接口提供一个一致的界面,使得子系统更容易使用。

kotlin">class SubsystemA {fun operationA() {println("Subsystem A operation")}
}class SubsystemB {fun operationB() {println("Subsystem B operation")}
}class Facade {private val subsystemA = SubsystemA()private val subsystemB = SubsystemB()fun operation() {subsystemA.operationA()subsystemB.operationB()}
}// 使用
fun main() {val facade = Facade()facade.operation()
}

行为型模式(Behavioral Patterns)

策略模式(Strategy Pattern)

定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换。

kotlin">interface Strategy {fun execute()
}class ConcreteStrategyA : Strategy {override fun execute() {println("Executing Strategy A")}
}class ConcreteStrategyB : Strategy {override fun execute() {println("Executing Strategy B")}
}class Context(private var strategy: Strategy) {fun setStrategy(strategy: Strategy) {this.strategy = strategy}fun executeStrategy() {strategy.execute()}
}// 使用
fun main() {val context = Context(ConcreteStrategyA())context.executeStrategy()context.setStrategy(ConcreteStrategyB())context.executeStrategy()
}
观察者模式(Observer Pattern)

定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。

kotlin">interface Observer {fun update()
}class ConcreteObserver : Observer {override fun update() {println("Observer updated")}
}class Subject {private val observers = mutableListOf<Observer>()fun addObserver(observer: Observer) {observers.add(observer)}fun removeObserver(observer: Observer) {observers.remove(observer)}fun notifyObservers() {for (observer in observers) {observer.update()}}
}// 使用
fun main() {val subject = Subject()val observer = ConcreteObserver()subject.addObserver(observer)subject.notifyObservers()subject.removeObserver(observer)subject.notifyObservers()
}
命令模式(Command Pattern)

将请求封装成对象,从而使得您可以用不同的请求对客户进行参数化。

kotlin">interface Command {fun execute()
}class ConcreteCommand(private val receiver: Receiver) : Command {override fun execute() {receiver.action()}
}class Receiver {fun action() {println("Receiver action")}
}class Invoker {private lateinit var command: Commandfun setCommand(command: Command) {this.command = command}fun executeCommand() {command.execute()}
}// 使用
fun main() {val receiver = Receiver()val command = ConcreteCommand(receiver)val invoker = Invoker()invoker.setCommand(command)invoker.executeCommand()
}
责任链模式(Chain of Responsibility Pattern)

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合。

kotlin">abstract class Handler {var nextHandler: Handler? = nullfun handleRequest(request: String) {if (canHandle(request)) {process(request)} else {nextHandler?.handleRequest(request)}}protected abstract fun canHandle(request: String): Booleanprotected abstract fun process(request: String)
}class ConcreteHandlerA : Handler() {override fun canHandle(request: String) = request == "A"override fun process(request: String) {println("Handler A processed $request")}
}class ConcreteHandlerB : Handler(){override fun canHandle(request: String) = request == "B"override fun process(request: String) {println("Handler B processed $request")}
}// 使用
fun main() {val handlerA = ConcreteHandlerA()val handlerB = ConcreteHandlerB()handlerA.nextHandler = handlerBhandlerA.handleRequest("A")handlerA.handleRequest("B")
}

这些示例展示了Kotlin中如何实现一些常见的设计模式。每个模式都有其特定的用途和场景,选择适合的模式可以大大提升代码的可维护性和扩展性。

我有多年软件开发经验,精通嵌入式STM32,RTOS,Linux,Ubuntu, Android AOSP, Android APP, Java , Kotlin , C, C++, Python , QT。 如果您有软件开发定制需求,请联系我,电子邮件: mysolution@qq.com


http://www.ppmy.cn/ops/89474.html

相关文章

悬而未决:奇怪的不允许跨域CORS policy的问题

我在本地HBuilderX中进行预览写好的前端网页&#xff0c;它里面用了ajax访问了远程服务器的后端API网址&#xff0c;不出意外地报不允许跨域访问的错了&#xff1a;Access to XMLHttpRequest at ‘http://xxx.com/MemberUser/login’ from origin ‘http://mh.com’ has been b…

江科大/江协科技 STM32学习笔记P17

文章目录 一、TIM输入捕获输入捕获与输出比较的关系频率测量测频法测周法 输入捕获的电路异或门的执行逻辑 输入捕获通道主从触发模式输入捕获基本结构PWMI基本结构输入捕获模式测频率main.c 输入捕获模式测占空比main.c 一、TIM输入捕获 输入捕获与输出比较的关系 在输出比较中…

RabbitMQ高级特性 - 非持久化 / 持久化(交换机、队列、消息)

文章目录 RabbitMQ 持久化机制概述实现非持久化&#xff08;交换机、队列、消息&#xff09;实现持久化&#xff08;交换机、队列、消息&#xff09; RabbitMQ 持久化机制 概述 前面讲到了 生产者消息确认机制 和 消费者消息确认机制&#xff0c;保证了消息传输的可靠性&#…

安装Docker以及安装过程中的错误解决

一、纯享版教程&#xff0b;操作截图 环境&#xff1a;centOs 7 FinalShell &#xff01;&#xff01;&#xff01;此教程针对第一次安装docker的友友&#xff0c;如果已经安装过且报错的朋友&#xff0c;请移步报错合集。 1.卸载旧版本&#xff08;无论是否安装过都建议执…

Tooltip 文字提示

在偶然维护前端开发时&#xff0c;遇到页面列表中某个字段内容太长&#xff0c;且该字段使用了组件显示&#xff0c;导致不能使用纯文本得那个省略号代替显示得css样式效果&#xff0c;如下 所以只能另辟溪路了&#xff0c; 1、最开始想到是使用横向滚动得效果来实现&#xff…

第一阶段面试问题(前半部分)

1. 进程和线程的概念、区别以及什么时候用线程、什么时候用进程&#xff1f; &#xff08;1&#xff09;线程 线程是CPU任务调度的最小单元、是一个轻量级的进程 &#xff08;2&#xff09;进程 进程是操作系统资源分配的最小单元 进程是一个程序动态执行的过程&#xff0c;包…

成为大佬之路--linux软件安装使用第000000040篇-linux操作文件和文件夹常用命令

1.创建文件 touch 文件名 下面命令创建了AscendKing.txt文件 然后过滤只要包含AscendKing的文件和文件夹 [rootVM-24-14-centos opt]# touch AscendKing.txt [rootVM-24-14-centos opt]# ls -l AscendKing* -rw-r--r-- 1 root root 0 7月 31 23:13 AscendKing.txt [rootVM-…

Redis高可用之持久化,以及reids的性能管理

一、redis高可用&#xff1a; 在集群当中有一个非常重要的指标&#xff0c;提供正常服务的时间的百分比&#xff08;365天&#xff09;99.9% redis的高可用含义更加宽泛&#xff0c;正常服务是指标之一&#xff0c;数据容量的扩展&#xff0c;数据的安全性 在redis中实现高可…