设计模式 - 享元模式 Flyweight Pattern

一、概念

尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。当程序中存在大量相似对象,每个对象之间只是根据不同的使用场景有些许变化时。

|--------------------------|---------------------------|
| Flyweight 享元接口 | 定义所有对象共同的操作。 |
| Concrete Flyweight 具体享元类 | 具体的要被共享的对象,内部保存需要共享的内部状态。 |
| Flyweight 享元工厂 | 管理享元对象的创建和复用。 |

二、实现

2.1 享元接口

Kotlin 复制代码
interface IChess {
    fun move(column: Int, row: Int)
}

2.2 具体享元类

Kotlin 复制代码
enum class ChessColor {
    BLACK, WHITE
}

class Chess(
    val color: ChessColor
) : IChess {
    override fun move(column: Int, row: Int) = println("$color 棋子颜色走到了【行$column】【列$row】处")
}

2.3 享元工厂

Kotlin 复制代码
class ChessFactory {
    companion object {
        //用来存储已创建对象的容器
        private val chessContainer = mapOf<ChessColor, IChess>()
        //已有匹配对象则复用,未找到则创建新对象
        fun getChess(chessColor: ChessColor): IChess {
            return chessContainer[chessColor] ?: Chess(chessColor)
        }
    }
}

2.4 使用

Kotlin 复制代码
fun main() {
    ChessFactory.getChess(ChessColor.WHITE).move(3,2) //WHITE 棋子颜色走到了【行3】【列2】处
    ChessFactory.getChess(ChessColor.BLACK).move(5,4) //BLACK 棋子颜色走到了【行5】【列4】处
}
相关推荐
SharpCJ13 小时前
Android 开发者为什么必须掌握 AI 能力?端侧视角下的技术变革
android·ai·aigc
_李小白13 小时前
【OSG学习笔记】Day 38: TextureVisitor(纹理访问器)
android·笔记·学习
JJay.14 小时前
Kotlin 高阶函数学习指南
android·开发语言·kotlin
jinanwuhuaguo14 小时前
截止到4月8日,OpenClaw 2026年4月更新深度解读剖析:从“能力回归”到“信任内建”的范式跃迁
android·开发语言·人工智能·深度学习·kotlin
JJay.14 小时前
Android Kotlin 协程使用指南
android·开发语言·kotlin
BLUcoding15 小时前
Android 布局介绍
android
summerkissyou198715 小时前
android-蓝牙-状态和协议值总结及监听例子
android·蓝牙
徒 花15 小时前
数据库知识复习05
android·数据库
qqxhb17 小时前
26|Agent 设计模式:ReAct、Plan-and-Solve 与反射
设计模式·react模式·plan-and-solve·reflection模式
提子拌饭13317 小时前
番茄时间管理:鸿蒙Flutter 实现的高效时间管理工具
android·flutter·华为·架构·开源·harmonyos·鸿蒙