A Way to implement Abstract Class In Flex

A Way to implement Abstract Class In Flex

It’s a fact that, until now(3.0) the ActionScript doesn’t implement the abstract class, it has Interface, but the abstract class is very useful when you have some logic that is fixed, and these class extends the class have some same methods(logic), and some other methods should be implemented in the subclasses, we should prevent the customer(of the super class) instantiating the super class. Compare to Interface, the abstract emphasize the “extending”, which means code reusing. But the Interface is more flexiable.

Okey, I found an article which introduce a way to implement the abstract class, but the way is not that perfect, it can implement the “Abstract” in runtime, it can’t check the error in complie time if the customer(of the super class) try to new the instance of the super class.

And, the runtime error is not recommended. There is no free lunch, to Force the AS3 to do something which is not native may cost a lot, In this case , you should do think carefully in your projects.

The following are copied from http://joshblog.net/2007/08/19/enforcing-abstract-classes-at-runtime-in-actionscript-3/, by JOSH TYNJALA.

As you probably know, abstract classes are not a language feature of ActionScript 3. If you are unfamiliar with the concept of an abstract class, let me explain. Think of an abstract class as a super-powered interface. It defines a series of functions that must be implemented, and it cannot be instantiated directly. It goes a step beyond an interface because it also defines some functions that are already fully implemented.

To use an analogy, all electronic devices generally have the same connector to plug into the wall. However, not all electronics have the same purpose. A coffee maker and a DVD player do very different things. We could make an interface IElectronicDevice to make sure they all have a plugIntoWall() function, but then every device will need to re-implement the common wall plug functionality that doesn’t differ very often. By making a class AbstractElectronicDevice, we can implement the wall plug functionality once, and all subclasses of AbstractElectronicDevice will be able to use it without re-implementing the same code.

The problem, of course, is that the coffee maker and DVD player have different controls for turning power on and off. The coffee maker might have a switch, while the DVD player has a button. We can’t implement the togglePower() function in AbstractElectronicDevice because many electronics will have different controls, so we need some way to force all subclasses of AbstractElectronicDevice to implement this function themselves. Using the methods developed to enforce Singletons in ActionScript 3 as a guide, I’ve found a way to enforce the abstractness of a class at runtime upon instantiation.

There are two main parts to enforcing an abstract class. First, we must stop a developer from instantiating the abstract class directly. To do this, the constructor needs a little special sauce. Since anyone can create an instance of a public class by simply using the new keyword, we need the constructor of our abstract class to require a parameter that only subclasses will be able to pass. Second, we must ensure that a developer implements functions that the abstract class has defined, but not implemented.

Stopping Direct Instantiation of an Abstract Class

The magic bean to stop a developer from instantiating a class directly is one keyword: this. You don’t have access to an instance of a class until after you call a constructor, so only an instance of a subclass will be able to pass a reference to itself to the super class. Let’s look at some code to help make things clearer.

The instance of MyAbstractType expects to receive a reference to itself as the first parameter in the constructor. If it does not, an error will be thrown.

package com.joshtynjala.abstract

{

    import flash.errors.IllegalOperationError;

 

    public class MyAbstractType

    {

       public function MyAbstractType(self:MyAbstractType)

       {

           if(self != this)

           {

              //only a subclass can pass a valid reference to self

              throw new IllegalOperationError("Abstract class did not receive reference to self. MyAbstractType cannot be instantiated directly.");

           }

       }

    }

}

Only MyConcreteType and other subclasses of MyAbstractType will be able to pass a reference to the instance to their super() constructors. Notice that users of MyConcreteType don’t need to know that it extends an abstract class. The signature of the MyConcreteType’s constructor can be completely different than MyAbstractType.

package com.joshtynjala.abstract

{

    public class MyConcreteType extends MyAbstractType

    {

       public function MyConcreteType()

       {

           //pass "this" to clear the abstract check

           super(this);

       }

    }

}

 

Forcing Implementation of Functions in Subclasses

Next, like with an interface, we need to force subclasses of our abstract class to implement specific functions. Ideally, we want this enforcement to happen immediately when the object is created (to make bugs visible as early as possible). After we check that the user isn’t trying to instantiate the abstract class directly, we should check to be sure the unimplemented methods are overridden. We can do by checking the results from theflash.utils.describeType() function against a list of unimplemented methods in the abstract class. Again, a little code should give us a clearer picture.

In MyAbstractType, after we check for a reference to the self parameter, we build a list of unimplemented functions in an Array. Next, we use describeType()to get a list of the methods declared in the instance. If a subclass of MyAbstractType overrides a method, the declaredBy attribute in the method XML will specify the name of the subclass rather than MyAbstractType.

package com.joshtynjala.abstract

{

    import flash.errors.IllegalOperationError;

    import flash.utils.describeType;

    import flash.utils.getQualifiedClassName;

 

    public class MyAbstractType

    {

       public function MyAbstractType(self:MyAbstractType)

       {

           if(self != this)

           {

              //only a subclass can pass a valid reference to self

              throw new IllegalOperationError("Abstract class did not receive reference to self. MyAbstractType cannot be instantiated directly.");

           }

 

           //these functions MUST be implemented in subclasses

           var unimplemented:Array = [mustBeOverridden];

 

           //get the fully-qualified name the abstract class

           var abstractTypeName:String = getQualifiedClassName(MyAbstractType);

 

           //get a list of all the methods declared by the abstract class

           //if a subclass overrides a function, declaredBy will contain the subclass name

           var selfDescription:XML = describeType(this);

           var methods:XMLList = selfDescription.method.(@declaredBy == abstractTypeName && unimplemented.indexOf(this[@name]) >= 0);

 

           if(methods.length() > 0)

           {

              //we'll only get here if the function is still unimplemented

              var concreteTypeName:String = getQualifiedClassName(this);

              throw new IllegalOperationError("Function " + methods[0].@name + " from abstract class " + abstractTypeName + " has not been implemented by subclass " + concreteTypeName);

           }

       }

 

       //implemented

       public function alreadyImplemented():void

       {

           trace("Don't forget to list me in the Array of valid functions.");

       }

 

       //unimplemented

       public function mustBeOverridden(param:String):void {};

    }

}

 

Now, in MyConcreteType, we can implement the mustBeOverridden() function. If we do not, an error will be thrown. To be certain, try commenting out the implementation of mustBeOverridden() in MyConcreteClass. If you instantiate it, you will receive a runtime error.

package com.joshtynjala.abstract

{

    public class MyConcreteType extends MyAbstractType

    {

       public function MyConcreteType()

       {

           //pass "this" to clear the abstract check

           super(this);

       }

 

       //implemented

       override public function mustBeOverridden(param:String):void

       {

           trace("param:", param);

       }

    }

}

Conclusions

As you probably noticed, the first part of implementing an abstract class is very simple. Making the abstract class receive a reference to itself enforces subclassing, and it can be done in only a few lines of code. The second part, making an abstract class work like an interface, requires a lot more code, and it may be more prone to errors. You, as a developer, must remember to add all the unimplemented methods to the Array in the constructor. Additionally, if the class gets large, I can imagine that calling describeType() often enough could lead to performance problems. In most cases, as long as you keep your classes clean, it should work well. I highly recommend the subclass enforcement, but I wouldn’t be heartbroken if you feel that checking for unimplemented methods is overkill.

Source code for this tutorial is available for download. It includes all the code above plus an extra implementation (for comparison) of the “electronic device” example I described at the beginning. It’s all under the terms of the MIT license.

 

Yes, it is really a good idea to implement the “Abstract Class”, but the checking is postponed to runtime, then some defects appear:

  1. Cost

May be it costs too much, you have to call describeType, this is really costing, especially when you have to create a lot of instances of subclasses.

 

转载于:https://www.cnblogs.com/Bill_Lee/archive/2011/03/11/1981797.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/475701.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

测试网络机顶盒的软件,2018网络机顶盒装机必备的几款系统工具,亲测好用

很多用户都喜欢比较网络机顶盒的配置,可是配置固然重要,如果没有好的日常保护,网络机顶盒受损程度也会很大。高配置的网络机顶盒在长时间使用后,也会出现卡顿,运行变慢等问题。今天给大家介绍几款系统工具,…

测试一体机风扇分贝软件,9款小风扇深度横评,风力、噪音测试加拆解,告诉你谁最值得买...

炎热的夏天又又又来了!虽然现在家里、办公室都有空调,但是当我们刚从暴热的室外进入室内时,空调还是很难让我们快速拥有舒爽温度,很多人都会选择一个台式小风扇作为辅助降温产品。但市面上的风扇品牌繁多,怎么才能选择…

LeetCode 1276. 不浪费原料的汉堡制作方案(解方程)

1. 题目 圣诞活动预热开始啦,汉堡店推出了全新的汉堡套餐。 为了避免浪费原料,请你帮他们制定合适的制作计划。 给你两个整数 tomatoSlices 和 cheeseSlices,分别表示番茄片和奶酪片的数目。 不同汉堡的原料搭配如下: 巨无霸汉…

IBM软件服务创新运用 提升市民生活质量

加拿大安大略省温莎-埃塞克斯区(Windsor-Essex)近日宣布,通过采用IBM公司的社交商务技术显著改善了当地市民的生活质量。 通过对IBM软件及服务的创新运用,不仅当地人群发作哮喘的情况有所缓解,一家本地汽车制造厂也实现了多元化经营&#xff…

怎么给域账号映射服务器,如何给每个域用户映射网络驱动器?

如何给每个域用户映射网络驱动器?即每个用户都可以在“我的电脑”中看到这个网络驱动器,并且赋予不同的权限。该如何实现呢?你可以使用,net use 命令来做啊net usr z: \\192.168.2.1\mcse passwoed /user:username--- 洛洛根据我的经验&#…

LeetCode 1297. 子串的最大出现次数

1. 题目 给你一个字符串 s ,请你返回满足以下条件且出现次数最大的 任意 子串的出现次数: 子串中不同字母的数目必须小于等于 maxLetters 。子串的长度必须大于等于 minSize 且小于等于 maxSize 。 示例 1: 输入:s "aaba…

PASCAL不仅仅是语言

PASCAL是一种计算机通用的高级程序设计语言,但不仅仅是语言。如下:int PASCAL WinMain(...){......}WinMain函数前的PASCAL是什么意思呢?PASCAL是函数在调用时,针对参数的压栈约定(即参数从右向左压栈),函数返回时需要重新调整堆栈…

计算机摄像头打不开,电脑摄像头打不开、用不了怎么办(操作简单),这几步你要了解...

有时候我们会遇到在开视频时电脑无法打开摄像头,这有可能是摄像头本身就有问题,也有可能是因为权限设置美没有到位,导致摄像头不能打开。今天咱们来解决一下,电脑摄像头无法打开的问题。工具/材料鲁大师或者360驱动大师等可以修改…

jsp 内置的对象的简要概述(转)

JSP 内置对象简要概述 (1) HttpServletRequest 类的 Request 对象 作用:代表请求对象,主要用于接受客户端通过 HTTP 协议连接传输到服务器端的数据。 (2) HttpServletResponse 类的 Respone 对象 作用:代表响应对象,主要用于向客…

LeetCode 684. 冗余连接(并查集)

1. 题目 在本问题中, 树指的是一个连通且无环的无向图。 输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。 结果图是一个以边组成的二维数…

fiddler怎么修改服务器返回数据,基于Fiddler实现修改接口返回数据进行测试

方法介绍与比对在测试的过程中,有的需求是这样的,它需要你修改接口返回的数据,从而检查在客户端手机app内是否显示正确,这也算是一种接口容错测试,接口容错测试属于app性能(专项)测试的其中一种。通过Fiddler我们可以有…

Form界面设置只读

很多时候,根据单据的状态的变化,要控制单据是否只读。 常用的form子程序: SET_BLOCK_PROPERTY(REQUEST_HEADERS_V,INSERT_ALLOWED,PROPERTY_TRUE);SET_BLOCK_PROPERTY(REQUEST_HEADERS_V,UPDATE_ALLOWED,PROPERTY_TRUE);SET_BLOCK_PROPERTY(R…

LeetCode 886. 可能的二分法(着色DFS/BFS/拓展并查集)

文章目录1. 题目2. 解题2.1 DFS2.2 BFS2.3 并查集1. 题目 给定一组 N 人(编号为 1, 2, …, N), 我们想把每个人分进任意大小的两组。 每个人都可能不喜欢其他人,那么他们不应该属于同一组。 形式上,如果 dislikes[i…

css scale 元素不放大,列元素上的CSS 3动画“transform:scale”对chrome不起作用

我在Chrome v44中遇到一个问题,我尝试使用“transform:scale(1.1)”放大列项目中的图像,动画不起作用…如果我尝试使用firefox,它运行良好!我认为问题是由于chrome,但我想知道是否有人找到了解决方法..column-wrap {columns: 3;}.column-item {backgroun…

js中如果无法获取某个html属性,例如自定义了一个dir属性,但获取总是为空,尝试换个词,因为可能什么关键词冲突了。...

js中如果无法获取某个html属性,例如自定义了一个dir属性,但获取总是为空,尝试换个词,因为可能什么关键词冲突了。转载于:https://www.cnblogs.com/kenkofox/archive/2011/03/26/1996416.html

LeetCode 685. 冗余连接 II(并查集)

1. 题目 在本问题中,有根树指满足以下条件的有向图。该树只有一个根节点,所有其他节点都是该根节点的后继。 每一个节点只有一个父节点,除了根节点没有父节点。 输入一个有向图,该图由一个有着N个节点 (节点值不重复1, 2, …, N…

prototype.js ajax.request,javascript – Prototype和Ajax.Request范围

我在原型的Ajax.Request类中获取正确的范围时遇到了麻烦.我要做的是编写一个包含ajax请求的简单API:API Class.create({initialize:function(api_token){this.api_token api_token;this.request_uri new Template(/api/#{api_token}/#{resource}.json);this.stat…

红黑树的c++完整实现源码

红黑树的c完整实现源码 作者:July、saturnman。时间:二零一一年三月二十九日。出处:http://blog.csdn.net/v_JULY_v。声明:版权所有,侵权必究。------------------------------------------- 前言: 本人…

[Kesci] 新人赛 · 员工满意度预测

文章目录1. 导入工具包2. 读取数据3. 特征处理3.1 数字特征归一化3.2 文字特征处理3.3 特征合并4. 定义模型训练5. 预测6. 新人赛结果竞赛地址 使用 sklearn Pipeline 模板 1. 导入工具包 %matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.rcPar…

webusercontrol ajax,ASP.NET页面使用AjaxPro2完成JS调用后台方法

一、首先下载AjaxPro.2.dll(附下载地址)百度网盘链接:https://pan.baidu.com/s/1r87DE1Tza9F4NbJwTCS1AQ提取码:10p6二、在Visual studio中创建空Web项目,并将AjaxPro.2.dll复制到bin目录下,包括在项目中三、打开Web.config文件&a…