设计模式 - 享元模式 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】处
}
相关推荐
Jomurphys36 分钟前
设计模式 - 组合模式 Composite Pattern
android·设计模式·组合模式
.豆鲨包39 分钟前
【Android】深入理解Window和WindowManager
android·java
pandarking2 小时前
[CTF]攻防世界:ez_curl
android·web安全·网络安全
hjlgs10 小时前
framework修改快速验证
android
游戏开发爱好者810 小时前
iOS 开发者的安全加固工具,从源码到成品 IPA 的多层防护体系实践
android·安全·ios·小程序·uni-app·cocoa·iphone
安卓理事人10 小时前
安卓内存泄露排查LeakCanary
android
秃了也弱了。12 小时前
MySQL空间函数详解,MySQL记录经纬度并进行计算
android·数据库·mysql
.豆鲨包12 小时前
【Android】Binder机制浅析
android·binder
Nerve14 小时前
GooglePay: API 文档
android·google