The prototype pattern defines a copy()
or clone()
method on all classes that follow the prototype pattern. Instead of creating new instances of those objects with the constructor, new instances are obtained by calling the copy()
method. The cloned object will be an exact copy of the original object.
Often, the prototype pattern will be implemented with a shared registry in the form of a factory method that would return the original source object to be cloned. In Swift, this pattern is usually implemented with the help of the NSCopying
protocol.
If you're using value types, you will not find yourself needing to implement the prototype pattern, as value types implement copy-on-write.
Let's use our Article
object from the previous example again, but this time as a class, so we don't benefit from the copy-on-write given by the value types:
class Article { private(set) var id: String let title: String let message: String let author: String...