โ Back to Design Patterns
๐งฌ
Creational
Prototype
Creates new objects by cloning an existing instance rather than constructing from scratch.
The Problem
Creating a new object is expensive or complex. You need a copy that starts as an exact replica of an existing one, with only a few differences.
How It Works
- โบCloning is often faster than constructing from scratch
- โบDeep copy duplicates nested objects; shallow copy shares them โ know the difference
- โบClone preserves the internal state that may be hard to reconstruct externally
- โบThe client does not need to know the concrete class of the object
- โบUseful for creating "template" objects with preset defaults
When to Use
โObject construction is costly and a similar object already exists
โConfig or template objects shared as a starting point with minor variations
โWhen you need to copy objects without depending on their concrete classes
โUndo/redo โ snapshot the state by cloning before modification
Real-World Examples
๐
iOS
NSCopying / NSMutableCopying, UIImage copy, deep copy via NSKeyedArchiver
๐ค
Android
Kotlin data class .copy(), Parcelable, Bundle.clone()
๐
Web
structuredClone(), spread { ...obj }, Object.assign({}, obj)
Code Examples
Swift
final class Theme: NSCopying {
var primaryColor: String
var font: String
var isDark: Bool
init(color: String, font: String, dark: Bool) {
primaryColor = color; self.font = font; isDark = dark
}
func copy(with zone: NSZone? = nil) -> Any {
Theme(color: primaryColor, font: font, dark: isDark)
}
}
let light = Theme(color: "#FF4D1C", font: "SF Pro", dark: false)
let dark = light.copy() as! Theme
dark.isDark = true
dark.primaryColor = "#FF6B47"
print(light.isDark) // false โ original unchanged
print(dark.isDark) // true