DEV Community

Harald Bregu
Harald Bregu

Posted on

2

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay