Swift World: Design Patterns — Flyweight

Peng
SwiftWorld
Published in
1 min readMar 18, 2017

Flyweight is about sharing. It holds a pool to store objects. The client will reuse existing objects in the pool. In previous articles, we have a general interface for car and a specific sedan class as following. Each car

protocol Car {
var color: UIColor { get }
func drive()
}
class Sedan: Car {
var color: UIColor
init(color: UIColor) {
self.color = color
}
func drive() {
print("drive a sedan")
}
}

we also have built our factory which produces sedan. Generally, we have sedan in different colors in stock. When there are orders, we look up in our stock first and reuse it.

class Factory {
var cars: [UIColor: Car] = [UIColor: Car]()
func getCar(color: UIColor) -> Car {
if let car = cars[color] {
return car
} else {
let car = Sedan(color: color)
cars[color] = car
return car
}
}
}

Let’s get cars from factory.

let factory = Factory()
let redSedan = factory.getCar(color: .red)
redSedan.drive()

Util now, we’ve completed structural patterns. If you want to learn others, we list them here.

Thanks for your time. Please clap to get this article seen by more people. Please follow me by clicking Follow. As a passionate iOS developer, blogger and open source contributor, I’m also active on Twitter and GitHub.

--

--

Peng
SwiftWorld

Engineers are the artists of our generation.