As I said at the end of the section that you just read, the best way to understand the logic that drives the memento pattern is by creating a hands-on example that shows in a step-by-step format how a caretaker object can hold the state of a property that belongs to an originator. Based upon this premise, below I set up the example in question. It demonstrates progressively how the previously created "ArrayElementSelector" class has the capacity to retain the value of the "arrayIndex" property that belongs to the "ArrayProcessor." The corresponding code sample is as follows: try{ /* displays the following: $arrayProcessor->setArrayIndex(1); /* // move array index to nonexistent element of input array /* // move array index back to second element of input array by using caretaker object /* } As illustrated above, after instantiating the two objects required by the memento pattern, that is the originator (in this case, represented by the ArrayProcessor class), and the caretaker (as you know, the "ArrayElementSelector class), the first element of the inputted array is properly displayed. However, the actual capacity of the pattern is demonstrated when the "ArrayElementSelector" object stores the value of the "arrayIndex" property, before moving this index forward and trying to display a non-existent array element: // caretaker object holds up the value of array index Obviously, this condition fires up an exception and the script is halted. But, since the caretaker has previously maintained the state of the "arrayIndex" property, it's possible to go back and redisplay the second element of the inputted array. As you can imagine, this situation is demonstrated by the following lines of code: // move array index back to second element of input array by using caretaker object Now, after understanding how the originator and caretaker classes work together, I'm sure that you'll agree with me that the memento pattern comes in handy for maintaining the state of a particular class. Isn't this great? Wrapping up Over this first installment of the series, I explained the basics of how to apply the memento pattern in PHP 5. Aside from being introduced to the concepts of the originator and caretaker classes respectively, hopefully you learned how to store the state of a given class by using another one, which is indeed useful. However, this journey is not finished. In the last article of the series, I'll show you how to use the memento pattern to hold the state of a file reading class. I hope to see you there!
blog comments powered by Disqus |
|
|
|
|
|
|
|