views:

53

answers:

2

In ActionScript all constructors must be public. Sometimes however, it is not feasible to allow a user to create a new instance of a class (since the class might be tied to physical system resources,network sockets, etc).

Does anyony know if there is a way to make a class non-creatable in ActionScript? In essence, what I'm aiming for is:

public class SomeClass
{
    internal function SomeClass():void { }
    . . .
}

I suppose I could get around this by defining an interface and implementing it in an internal class, but that just doesn't feel right to me:

internal class ClassImpl implements ISomeClass
{
    . . . 
}

Suggestions?

+1  A: 

Here's a solution where a magic number is needed for a constructor to work. Hopefully this could be of help.

Extrakun
The link seems down atm. I did think of that myself, but didn't want to clutter the ctor with a 'magic' parameter. Thanks
cmroanirgo
+1  A: 

yeah, the safety argument trick ... :)

it's a good start, but with a simple number, it will only throw runtime errors, if you pass in numbers (plus there is a chance of 1/2^64 that you guess the right number ... :D) ... use this, if you want to have compile time errors as well (one stupid thing is, that you just can't set a type to be non-nullable, so null will always be a valid argument):

package  {
    public class Test {
     public function Test(enforcer:TestEnforcer) {
      if (enforcer == null) throw "haha, good try ... but, no! :P";
     }
     public static function create():Test {
      //do your cheks here
      return new Test(TestEnforcer.enf);
     }
    } 
}
class TestEnforcer {
    public function TestEnforcer() { }
    public static const enf:TestEnforcer = new TestEnforcer();
}

another approach is, to create public interface MyPrivateConstrClass and a private/internal class MyPrivateConstrClassImpl and have another function that'll instantiate MyPrivateConstrClassImpl, but let the return value of that function be of type MyPrivateConstrClass ... it's a little overkill, but 100% compile and runtime safe ...

back2dos
You could simplify this implementation by simply having a private static field of type Object and performing a strictly equals (===) check against it.
Richard Szalay
yes and no ... the point of this approach is, that you cannot pass any valid value to the ctor, since TestEnforcer is a private class ... there's always null of course ...
back2dos