简体   繁体   English

AS3使用基类对象来创建扩展类的实例

[英]AS3 using base class object to create instance of extended class

I have a custom class that extends MovieClip . 我有一个扩展MovieClip的自定义类。 The idea is that it allows for storing extra variables and information about the MovieClip . 这个想法是它允许存储有关MovieClip额外变量和信息。

public class MapObject extends MovieClip
{
    private var cellX:int;
    private var cellY:int;

    public function MapObject()
    {
    }
 }

I have several MovieClips (.swf files) that I load at runtime. 我有几个在运行时加载的MovieClips (.swf文件)。 The problem is, how can I make these MovieClip objects actually become MapObject objects? 问题是,如何让这些MovieClip对象实际成为MapObject对象?

I've tried : 我试过了 :

var mapObject:MapObject = myMovieClip as MapObject;

but it gives null 但它给出了null

PS. PS。 I know you can add variables dynamically to MovieClips, but I don't really want to do that. 我知道你可以动态地向MovieClip添加变量,但我真的不想这样做。

You can't change the class hierarchy without changing the code. 您无法在不更改代码的情况下更改类层次结构。 You would have to go in each class definitions to change the parent class to MapObject instead of MovieClip . 您必须在每个类定义中将父类更改为MapObject而不是MovieClip

There is an easy and clean solution which consists in using a decorator: 有一个简单而干净的解决方案,包括使用装饰器:

public class MapObject {

    private var mc:MovieClip;
    private var cellX:int;
    private var cellY:int;

    public class MapObject(mc:MovieClip) {
        this.mc = mc;
    }

    public function get movieClip():MovieClip {
        return mc;
    }
}
...

var wrapper:MapObject = new MapObject(new MyMovieClip());
...

container.addChild(wrapper.movieClip);

It's a wrapper that takes an instance of another class (in your case MovieClip) to add functionality. 它是一个包装器,它接受另一个类的实例(在你的情况下是MovieClip)来添加功能。 It's very powerful because you don't have to go and change each of your subclasses any time you change MapObject . 它非常强大,因为您无需在更改MapObject时更改每个子类。 This principle is called composition over inheritance . 这个原则被称为组合而不是继承

In your case, all methods and properties of MovieClip are public so you would just write mc.play() instead of this.play() . 在您的情况下, MovieClip所有方法和属性都是公共的,因此您只需编写mc.play()而不是this.play()

See the details about the Decorator design pattern . 查看有关Decorator设计模式详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM