OOP problem: Extending a class, override functions and jQuery-like syntax

寵の児 提交于 2019-12-06 01:43:13
Vincent Mimoun-Prat

This problem is quite common. The design pattern you are using is called Fluent Interface and if you Google "Fluent Interface Inheritance", you'll find lots of questions and very few answers.

A common way to solve it in C#, Java and C++ is to use templates. However, I cannot tell how to implement the same in AS3, I found this topic that might help you.

If you want function to be listed by code completion, it must be there. This rules out any runtime discovery methods. I would add to Chain something like this:

public function animate(args:Object, time:int):Chain {
    throw new Error("Animate is supported only on ChainTween");
}

to be overridden in ChainTween. Don't think it's such a big stretch.

Following the structure of the Chain class, it should be possible ( and somehow logical ) to use the add method to call the animate method... Not knowing more about the Chain class , it's difficult to be more accurate , but in theory it would seem possible... It would require adding a new argument to the add method.

var chain:ChainTween = new ChainTween();
var params:Object = {x:200};
chain.wait(100).add(animate, 300 , params).wait(300);

alxx has a point, it would seem that something has to give somehow, unlike Javascript, AS3 is a strongly typed language , this is the very cause of your limitations. If you need to implement methods as specific as rotate, fadeOut , you may not have a whole lot of solutions available. Those methods will either return a ChainTween, a Chain or an Object, and you're dismissing both Object and * ...

Somehow, I still think that adding the rotate , fadeOut or animate method with add() ( or any other method you may create for that purpose ) is more in line with Chain's design.

You could try returning * instead of Chain but this removes code hinting.

if i were you i'd created an IChain interface describing only core functions (add, wait etc)

I would go for the already suggested interface idea. Wait would return something like 'IChainTween' which only contains methods to configure a ChainTween and also a function like 'then' which returns the original Chain.

package
{
    public interface IChainTween
    {
        function doSomething():IChainTween;
        ...
        function then():IChain;
    }
}

package
{
    public class ChainTween implements IChainTween
    {
        private originalChain:IChain;
        public function ChainTween(IChain chain)
        {
            originalChain = chain;
        }
        ...
        public function doSomething():IChainTween
        {
            return this;
        }
        public function then():IChain
        {
            return originalChain;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!