Design Patterns in ActionScript-Prototype

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.

  1. public interface Cloneable
  2. {
  3. function   clone () : Object
  4. }

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.

clip_image001

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. DownloadDownload Full Project

Enjoy!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值