As I expressed in the section that you just finished reading, one of the most educational ways to understand how the memento pattern works is by creating a practical example where the two classes are put to work together. In this case, you'll see how the "FileDataSeeker" class defined in a previous section is capable of maintaining the value of the "filePointer" property, which belongs to the "FileDataReader" class. Let us assume that there is a sample text file containing the following lines of basic data: This is the line 1 of data file. Here is the short script that demonstrates the functionality provided by the memento pattern. Please examine the code sample below: try{ /* // move file pointer to last line of data file /* // store value of file pointer onto caretaker object /* // move file pointer back to last element of data file /* With reference to the example shown above, there are some interesting things to note. First, notice how after instantiating the respective originator and caretaker objects, the first line included in the sample data file is read and displayed. So far, there is nothing unexpected, right? However, things become a little more exciting when the file reading object is pointed to a non-existent line of the mentioned data file. This throws an exception, and consequently the execution of the script is halted. However, since the value of its "filePointer" property was previously stored by the respective "FileDataSeeker" object, it's possible to move the pointer in question back to the last element of the data file. This condition is clearly illustrated by the following code snippet: // move file pointer back to last element of data file As you can see, this is where the memento pattern comes into its own, since the value of the mentioned file pointer property is retrieved from the caretaker object. Now do you see how the state of class can be tracked with this handy pattern? I suppose you do! As usual, feel free to incorporate your own modifications to all the classes that were shown in this tutorial. In this way you can expand your background on the memento pattern. Fun is already guaranteed! Final thoughts Sadly, we've come to the end of this series. In this pair of tutorials, I introduced the key points of how to apply the memento design pattern with PHP 5. As you saw, if you're looking for an accessible approach for keeping track of different properties that belong to a given class, indeed this pattern could be a good choice. See you in the next PHP tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|