views:

166

answers:

2

Is something like this possible in Actionscript?

Java:

URLFetcherFactory.setCreator(
    new IURLFetcherCreator() {
     public IURLFetcher create() {
      return new URLFetcher();
     }
    }
);

Actionscript:

?

I've been wondering about this and have been unable to find anything that indicates it's possible. Figured if it was possible, I'd be able to find an answer here. Thanks! Stackoverflow rocks!

A: 

Try this:

URLFetcherFactory.setCreator(
    new IURLFetcherCreator() {
            public function create():IURLFetcher  {
                    return new URLFetcher();
            }
    }
);
CookieOfFortune
A: 

You cannot create an instance of an interface. You can, however, create a factory class:

public class URLFetcherCreator : IURLFetcherCreator {
    private var _cls : Class;

    public URLFetcherCreator(Class cls) {
        this._cls = cls;
    }

    public function create() : IURLFetcher
    {
        return new cls();
    }
}

Alternatively, change setCreator to accept a Function that returns an IURLFetcher:

URLFetcherFactory.setCreator(
    function() : IURLFetcher {
        return new URLFetcher();
    }
);
Richard Szalay
Exactly! I like the second implementation the best, even though you lose the ability to check what type the function returns. That is more in-line with what I am trying to do. Thanks!
Yeah, it's a shame that AS3 doesn't support strongly typed delegates. Lambdas would be even better.
Richard Szalay

related questions