This article is a summary of my reading of Raywenderlich.com’s Design Patterns by Tutorials. The code in this article was modified according to my own ideas after READING the book. If you want to see the original book, please click the link to buy it.


The prototype pattern is a creation pattern that allows us to copy an object. It has two parts: 1) Copying protocol; Follow the Class type of the Copying protocol.

There are two types of replication: shallow and deep:

  • Shallow copy: A new instance is created, but instead of copying the properties of the original instance, all the properties point to the original instance.

  • Deep copy: Creates a new instance and copies the properties of the original instance.

When to use

Use this pattern when you want to copy an object.

A simple demo

In Objective-C, there is a NSCopying protocol that is still usable in Swift, but not very user-friendly, so let’s define one ourselves:

protocol Copying: class {
    init(_ prototype: Self)
}

extension Copying {
    func copy(a) -> Self {
        return type(of: self).init(self)}}Copy the code

First we define a Copying protocol and specify an initialization function that takes instances of the current type as parameters. The copy() method is then extended.

Next define a pet class and implement the Copying protocol:

class Pet: Copying {
    let name: String
    let weight: Double

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

    // MARK: - Copying

    required convenience init(_ pet: Pet) {
        self.init(name: pet.name, weight: pet.weight)
    }
}
Copy the code

Try the pet class we just defined:

let pet1 = Pet(name: "Lili", weight: 10)
let pet2 = pet1.copy()
print("pet1====name: \(pet1.name)====weight: \(pet1.weight)")
print("pet2====name: \(pet2.name)====weight: \(pet2.weight)")

/ / the result
pet1= = = =name: Lili= = = =weight: 10.0
pet2= = = =name: Lili= = = =weight: 10.0
Copy the code

The result is exactly the same, and we are done copying an instance.

After the

Welcome to join my Swift development group: 536353151.