AS3 - Abstract Classes

2019-03-22 14:25发布

How can I make an abstract class in AS3 nicely?

I've tried this:

public class AnAbstractClass
{
    public function toBeImplemented():void
    {
        throw new NotImplementedError(); // I've created this error
    }
}

public class AnConcreteClass extends AnAbstractClass
{
    override public function toBeImplemented():void
    {
        // implementation...
    }
}

But.. I don't like this way. And doesn't have compile time errors.

4条回答
趁早两清
2楼-- · 2019-03-22 15:06

In AS3 would just use interfaces to make sure all functions are implemented at compile time. I know it different but does the trick for an example such as the one above.

查看更多
三岁会撩人
3楼-- · 2019-03-22 15:07

abstract classes are not supported by actionscript 3. see http://joshblog.net/2007/08/19/enforcing-abstract-classes-at-runtime-in-actionscript-3/

the above reference also provides a kind of hackish workaround to create abstract classes in as3.

Edit
also see http://www.kirupa.com/forum/showpost.php?s=a765fcf791afe46c5cf4c26509925cf7&p=1892533&postcount=70

Edit 2 (In response to comment)

Unfortunately, you're stuck with the runtime error. One alternative would be to have a protected constructor.... except as3 doesn't allow that either. See http://www.berniecode.com/blog/2007/11/28/proper-private-constructors-for-actionscript-30/ and http://gorillajawn.com/wordpress/2007/05/21/actionscript-3-%E2%80%93-no-private-constructor/.

You may Also find these useful: http://www.as3dp.com/category/abstract-classes/ and, in particular, http://www.as3dp.com/2009/04/07/design-pattern-principles-for-actionscript-30-the-dependency-inversion-principle/

查看更多
贼婆χ
4楼-- · 2019-03-22 15:11
package 
{
    import flash.errors.IllegalOperationError;
    import flash.utils.getDefinitionByName;
    import flash.utils.getQualifiedClassName;
    import flash.utils.getQualifiedSuperclassName;

    public class AbstractClass 
    {
        public function AbstractClass()
        {
            inspectAbstract();
        }

        private function inspectAbstract():void 
        {
            var className : String = getQualifiedClassName(this);
            if (getDefinitionByName(className) == AbstractClass ) 
            {
                throw new ArgumentError(
                getQualifiedClassName(this) + "Class can not be instantiated.");
            }
        }

        public function foo():void
        {
            throw new IllegalOperationError("Must override Concreate Class"); 
        }
    }
}

package
{
    public class ConcreteClass extends AbstractClass
    {
        public function ConcreteClass()
        {
            super();
        }

        override public function foo() : void 
        {
            trace("Implemented");
        }
   }
}
查看更多
在下西门庆
5楼-- · 2019-03-22 15:11

As long as they don't permit non-public constructors in actionscript, you'd have to rely on run time errors for abstract classes and singletons.

查看更多
登录 后发表回答