When I want to write the Prototype pattern, I firstly look up the ActionScript 3.0 manual. I want to find out whether there is a clone method in Object class. If so, I will use this as an example. But, unfortunately, I can’t find this method in the Object class. Then I found the prototype attribute, but the explanation confused me. So, I decide to show you this pattern in my own way without using the Object class.
Firstly, you need to know the intent of this pattern. You can read the following text.
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
–By GOF BOOK
This pattern is about how to instantiate a new object. You may say, we could use the new operator to instantiate the object. Of course, you can do it in this way. But there are still some another things you need to considering, such as the new object can’t get any information from the current object. It just likes in some fantasy movies, the magician copy himself, and two or more magicians looks the same appears in the screen.
When the object has much the same with the existing object, you need to consider this pattern. By using this pattern, you can get a copy of the existing object.
Do it the simplest way, we provide an interface named Cloneable, and the concrete class will implement this interface.
- public interface Cloneable
- function clone():Object
And the concrete class named Magician. It implements the clone method, and returns and new magician with the current state.
The class diagram is as follows.
Now, you can use Magician.clone() to get a new instance. And the new instance will be the same as the existing one. If you want the classes be the same, this is a good way for you.
When you want to apply this pattern, I should tell you some thing more about this pattern. Have you ever heard deep copy and shallow copy? If you have ever heard that, I think you’re already what I will say next. If not, you’d better to get some information about those things.
If you use the shallow copy, the reference field of new object and old object will points to the same object. So, when you change the object via the old object. The new object will also be affected. So, be careful about the shallow copy. Download Full Project