Chapter 18: Flyweight Pattern
大綱
When should you use it?
The flyweight pattern is a structural design pattern that minimizes memory usage and processing
The flyweight pattern has objects, called flyweights, and a static method to return them.
The flyweight pattern is a variation on the singleton pattern.
In the flyweight pattern, you usually have multiple different objects of the same class.

When should you use it?
Use a flyweight in places where you would use a singleton, but you need multiple shared instances with different configurations.
Playground example
Flyweights are very common in UIKit. UIColor, UIFont, and UITableViewCell are all examples of classes with flyweights.
如何讓custom color也遵守Flyweights pattern?
What should you be careful about?
be careful about how big your flyweight memory grows.
you minimize memory usage for the same color, but you can still use too much memory in the flyweight store.
為什麼apple的UIColor只針對某些特定color是遵守Flyweights pattern, 像藍色,紅色。至於客製化顏色都弄成Flyweights pattern就會導致colorStore過於龐大。
Set bounds on how much memory you use or register for memory warnings and respond by removing some flyweights from memory
LRU (Least Recently Used) cache to handle this.
flyweight shared instance must be a class and not a struct. Structs use copy semantics
Tutorial project
希望每次切換tab可以切換指定的不同大小的字型。
每次切換都不需要再次產生instace因此可以利用Flyweight Pattern來處理。

Fonts Class
Key points
The flyweight pattern minimizes memory usage and processing.
This pattern has objects, called flyweights, and a static method to return them. It’s a variation on the singleton pattern.
When creating flyweights, be careful about the size of your flyweight memory. If you’re storing several flyweights, it’s still possible to use too much memory in the flyweight store.
Examples of flyweights include caching objects such as images, or keeping a pool of objects stored in memory for quick access.
Last updated