DEV Community

Harald Bregu
Harald Bregu

Posted on

Prototype design pattern in Swift

The Prototype design pattern is a creational pattern that allows for the creation of new objects by copying or cloning existing objects. This pattern can be useful in situations where creating new objects from scratch is expensive or time-consuming, or where objects need to be customized with different configurations or properties.

protocol Prototype {
    func clone() -> Prototype
}

class Sheep: Prototype {
    var name: String

    init(name: String) {
        self.name = name
    }

    func clone() -> Prototype {
        return Sheep(name: self.name)
    }

}

// Example usage
let originalSheep = Sheep(name: "Maria")
let clonedSheep = originalSheep.clone() as! Sheep

print(originalSheep.name) // Prints "Maria"
print(clonedSheep.name) // Prints "Maria"

clonedSheep.name = "Dolly"

print(originalSheep.name) // Prints "Maria"
print(clonedSheep.name) // Prints "Dolly"
Enter fullscreen mode Exit fullscreen mode

If you are interested in learning more about design patterns in Swift, you can check out my GitHub repository, where I have provided examples and explanations of various design patterns.

Top comments (0)