Concepts related to prototype patterns

Prototype mode creates new objects by cloning existing objects, which are prototypes.

The benefits of using this pattern

  • The code that creates the object is hidden, meaning that the code is invisible to the components that use it
  • Avoid repeated initialization.
  • Avoid dependency on class templates

When to use when you need to create new instances but don’t want to rely on class constructors. You can use this pattern

pit

  • Deep copy and shallow copy
  • Unstructured code (prototype objects must be exposed for copying)

Prototype pattern examples:

Swift automatically uses prototype mode when assigning a value type to a variable. Value types are defined using structs.

Let’s define an Appointment structure. Its structure is shown in the following code

import UIKit

/// Struct is a value type, and the default is deep copy
struct Appointment{
    var name:String
    var day:String
    var place:String

    func printDetail(label:String) {
        print("\(label) with \(name) on \(day) at \(place)")}}Copy the code

Instantiate a beerMeeting. Beermetting is then assigned to the workmeeting. And modify some values.

var  beerMeeting = Appointment(name: "Bob", day: "Mon", place: "BeiJing")
beerMeeting.printDetail(label: "beerMeeting")

var workMeeting = beerMeeting
workMeeting.name = "Alice"
workMeeting.day = "Fri"
//workMeeting.place = "Shanghai"

workMeeting.printDetail(label: "workmeeting")

let beerPointer = withUnsafePointer(to: &beerMeeting, { $0 })
let workPointer = withUnsafePointer(to: &workMeeting, { $0 })

print(beerPointer)
print(workPointer)

print(beerMeeting)
print(workMeeting)
Copy the code

Here is the printed result, which shows that Swift automatically made a deep copy of beerMetting.

beerMeeting with Bob on Mon at BeiJing
workmeeting with Alice on Fri at BeiJing
0x00000001142bc920
0x00000001142bc968
Appointment(name: "Bob", day: "Mon", place: "BeiJing")
Appointment(name: "Alice", day: "Fri", place: "BeiJing")
Copy the code

If you want to implement the stereotype pattern in reference types, you need to implement the NSCoping protocol.

The initial template for the SportStore application used in this article is here github.com/RockyAo/Des…

The sample code for this article is also available here (in the 02 folder) github.com/RockyAo/Des…