Chapter 14: Prototype Pattern

大綱

When should you use it?

  • The prototype pattern is a creational pattern that allows an object to copy itself.

    • A copying protocol that declares copy methods.

    • A prototype class that conforms to the copying protocol.

  • two different types of copies: shallow and deep.

    • A shallow copy: creates a new object instance, but doesn’t copy its properties. Any properties that are reference types still point to the same original objects.

      • For example, whenever you copy a Swift Array, which is a struct and thereby happens automatically on assignment, a new array instance is created but its elements aren’t duplicated.

    • A deep copy: creates a new object instance and duplicates each property as well.

      • For example, if you deep copy an Array, each of its elements are copied too. Swift doesn’t provide a deep copy method on Array by default

  • When should you use it?

    • Use this pattern to enable an object to copy itself.

Playground example

  • 目標: deep copy

  • Protocol - Copy

  • Prototype class

What should you be careful about?

  • by default it’s possible to pass a superclass instance to a subclass’s copy initializer.

    • This may not be a problem if a subclass can be fully initialized from a superclass instance. However, if the subclass adds any new properties, it may not be possible to initialize it from a superclass instance.

    • To mitigate this issue, you can mark the subclass copy initializer as “unavailable.” In response, the compiler will refuse to compile any direct calls to this method

Tutorial project

Key points

  • The prototype pattern enables an object to copy itself. It involves two types: a copying protocol and a prototype.

  • The copying protocol declares copy methods, and the prototype conforms to the protocol.

  • Foundation provides an NSCopying protocol, but it doesn’t work well in Swift. It’s easy to roll your own Copying protocol, which eliminates reliance on Foundation or any other framework entirely.

  • The key to creating a Copying protocol is creating a copy initializer with the form init(_ prototype:)

Last updated