AS3.0中抽象类的实现

AS3.0不支持抽象类。可以通过在构造函数里抛出异常来实现抽象类,也可以使用mimswright的抽象类工具包,项目地址,参考博客

 

通过mimswright的抽象类和抽象方法来实现,如果试图生成AbstractFun的实例,就会抛出异常:ERROR:An abstract class may not be instantiated.

 1 package com.cnblogs.matrix42.abstractexample  
 2 {  
 3     import com.mimswright.utils.AbstractEnforcer;
 4     public class AbstractFun  
 5     {  
 6         //抽象类的构造函数
 7         public function AbstractFun()
 8         {  
 9             AbstractEnforcer.enforceConstructor(this, AbstractFun);  
10             //TODO
11         }  
12         //抽象方法
13         public function toDo():void
14         {  
15             AbstractEnforcer.enforceMethod();  
16             //TODO 
17         }  
18     }  
19 } 
 1 package com.cnblogs.matrix42.abstractexample  
 2 {  
 3     public class ConcreteFun extends AbstractFun  
 4     {  
 5         public function ConcreteFun()
 6         {  
 7             //TODO
 8         }  
 9         public function toDo():void
10         {  
11             //TODO
12         }
13     }  
14 }

 

下面是其他的几种比较妙的实现方式,记录供参考:

1、

 1 package    
 2 {
 3     import flash.errors.IllegalOperationError;
 4     public class MyAbstractType
 5     {
 6         public function MyAbstractType(self:MyAbstractType)
 7         {
 8             if(self != this)
 9             {
10                 throw new IllegalOperationError("Abstract class did not receive reference to self. MyAbstractType cannot be instantiated directly.");
11             }
12         }
13     }
14 }
 1 package
 2 {
 3     public class MyConcreteType extends MyAbstractType
 4     {
 5         public function MyConcreteType()
 6         {
 7             super(this);
 8         }
 9     }
10 }

 

2、

 1 package
 2 {
 3     class AbstractClassA
 4     {
 5         protected var _allowInstance:Boolean = false;
 6         public function AbstractClassA()
 7         {
 8             if(!_allowInstance)  throw new Error("abstract");
 9         }
10     }
11 }
 1 package
 2 {
 3     class ClassB extends AbstractClassA
 4     {
 5         public function ClassB()
 6         {
 7             _allowInstance = true;
 8             super();
 9         }
10     }
11 }

 

3、

 1 package
 2 {
 3     class Abstract
 4     {
 5         public function Abstract():void
 6         {
 7             if(this["constructor"] == "[class Abstract]")
 8             {
 9                 throw new Error("...");
10             }
11         }
12     }
13 }

 

4、

 1 package
 2 {
 3     public class Abstract
 4     {
 5         public function Abstract ()
 6         {
 7             if (Object(this).constructor == Abstract) throw new Error('Error');
 8         }
 9     }
10 }

 

posted @ 2012-08-03 21:55  Matrix.42  阅读(648)  评论(0编辑  收藏  举报