释义
原型模式,暂存一个原型,当需要创建该类的对象的时候(尤其是需要大量该类对象的时候),直接从这个原型复制一个对象出来而不是从头开始创建。
接入Cloneable
需要被克隆的类必须接上Cloneable
,建议重写clone
方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Shape : Cloneable {
open var name: String? = null
public override fun clone(): Any? {
var clone: Any? = null
try {
clone = super.clone()
} catch (e: CloneNotSupportedException) {
e.printStackTrace()
}
return clone
}
}
|
子类
Circle
1
2
3
4
5
|
class Circle : Shape() {
override var name = "Circle"
...
}
|
Square
1
2
3
4
5
|
class Square : Shape() {
override var name = "Square"
...
}
|
Rectangle
1
2
3
4
5
|
class Rectangle : Shape() {
override var name = "Rectangle"
...
}
|
存入ShapeMap
创建ShapeCache
对象来存储ShapeMap
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class ShapeCache {
private var shapeMap: MutableMap<String, Shape> = mutableMapOf()
// 向缓存中放入Shape
fun loadCache(shape: Shape) {
shapeMap?.set("name", shape)
}
fun getShape(name: String): Shape {
return shapeMap.get(name)
}
}
|
使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
fun main() {
// 创建三个对象
val circle: Circle = Circle()
val square: Square = Square()
val rectangle: Rectangle = Rectangle()
// 创建缓存
val shapeCache: ShapeCache = ShapeCache()
// 将对象存入缓存
shapeCache.loadCache(circle)
shapeCache.loadCache(square)
shapeCache.loadCache(rectangle)
// 克隆
val circleClone: Circle = shapeCache.get("circle").clone() as Circle
val squareClone: Square = shapeCache.get("square").clone() as Square
val rectangleClone: Rectangle = shapeCache.get("rectangle").clone() as Rectangle
}
|