In the last article I wrote about Model-View-Controller design patterns that is present in almost every iOS application. This time I will try to reveal some secrets of two other design patterns – Memento and Proxy. I will show how to design an efficient data persistence mechanism with these two aforementioned approaches.
What the heck is Memento?
Quick definition:
“Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later”, Design Patterns, by the “Gang of Four” (Addison-Wesley, 1994)
Let’s say we have an object or thousands of objects and we want to store them when the user saves the state of the work/game/application or in dozens of other cases. A memento is an object that keeps the information about the state of the other object. Thus, the memento encapsulates information that can be used to recreate the original object.
To make the pattern work we need objects that fulfill roles of:
- originator – creates a memento with all information that is relevant for us and will be useful later to recreate the object,
- memento – stores the information about the state of the originator object
- caretaker – stores the memento somewhere in the memory.
Everything’s easy. The caretaker asks originator to create a memento. Originator creates the memento. However, the originator does not know how to save it. This is done by the caretaker, which takes the memento and stores it in the file system (for instance as a NSData or a plist). In case of loading the memento from the file system steps are analogical.
Cocoa Touch uses the Memento pattern in archiving, property list serialization and Core Data.
Aha, and what is this Proxy all about?
Quick definition:
“Provides a surrogate or placeholder for another object to control access to it.“, Design Patterns, by the “Gang of Four” (Addison-Wesley, 1994)
The main idea of the Proxy pattern is very easy. Let’s say we have an image we would like to present in our UIImageView. However, the image is located on the external server and we need to fetch it. So, in order to raise the user’s experience we are presenting the placeholder image and when the download is finished we update the photo. This is all about Proxy pattern.
We can apply Proxy pattern to an iOS app to lazy-load the data that is expensive in terms of memory usage. A virtual proxy object gives some sort of initial information of the object that will be loaded when the user requests it.
References:
Pro Objective-C Design Patterns for iOS, Carlo Chung
