一、概念
尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。当程序中存在大量相似对象,每个对象之间只是根据不同的使用场景有些许变化时。
|--------------------------|---------------------------|
| 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】处
}