享元模式

享元模式(Flyweight Pattern)

享元模式是一种结构性设计模式,可以最大程度地减少内存使用和处理。

此模式提供的对象均共享相同的基础数据,从而节省了内存。它们通常是不变的。

享元模式具有称为flyweights的对象,以及返回它们的静态方法

享元模式是单例模式的变体,在享元模式中,通常有多个相同类的不同对象。

使用举例

享元模式在UIKit中使用非常普遍,UIColor,UIFont,UITableViewCell都是使用享元模式的类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import UIKit
let red = UIColor.red
let red2 = UIColor.red
print(red === red2) // proves this is a flyweight
let color = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
let color2 = UIColor(red: 1, green: 0, blue: 0, alpha: 1)
print(color === color2) // proves this is NOT a flyweight
extension UIColor {
public static var colorStore: [String: UIColor] = [:]
public class func rgba(_ red: CGFloat,
_ green: CGFloat,
_ blue: CGFloat,
_ alpha: CGFloat) -> UIColor {
let key = "\(red)\(green)\(blue)\(alpha)"
if let color = colorStore[key] {
return color
}
let color = UIColor(red: red,
green: green,
blue: blue,
alpha: alpha)
colorStore[key] = color
return color
}
}
let flyColor = UIColor.rgba(1, 0, 0, 1)
let flyColor2 = UIColor.rgba(1, 0, 0, 1)
print(flyColor === flyColor2) // proves this is a flyweight class method

其他例子

  1. OC中的享元模式:https://www.jianshu.com/p/e3eb1fa44f83
  2. 咖啡例子:http://jackliu17.github.io/2016/06/05/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E4%BA%AB%E5%85%83/
  3. 在屏幕中画多个花:https://segmentfault.com/a/1190000012507640