Mahmoud Awad
Mahmoud Awad

Reputation: 103

How to instantiate classes only from inside another class in Haxe

I need to prevent class A from being instantiated anywhere but only from another class B, then class B can return the created instance of class A which can be used in any other class.

I understand that B could be a Factory in this example, I looked in the factory pattern in the Haxe code cookbook but it does not seem suit what I am looking for.

In my example class B is doing some work then should return the result in an instance of class A.

no one should be able to create an instance of class A because it is the result of the work that class B performs. anyone needs an instance of A should ask B to do the work and return the resulted A instance

hope I explained it clearly

Upvotes: 3

Views: 444

Answers (1)

Gama11
Gama11

Reputation: 34138

You would usually do this by using @:allow() metadata in combination with a private constructor:

A.hx:

class A {
    @:allow(B)
    private function new() {}
}

B.hx:

class B {
    public static function create():A {
        return new A(); // compiles
    }
}

Trying to instantiate A outside of B will result in a compiler error:

class Main {
    static function main() {
        new A(); // Cannot access private constructor of A
    }
}

Note that it's still possible to work around this by using @:access() or @:privateAccess metadata - in Haxe, nothing is ever truly private. It follows a philosophy of "the programmer knows best", which can be very powerful.

Also, you might want to declare A as @:final so nothing can subclass it, because subclasses can access private fields in Haxe. But again, this can be overriden with @:hack metadata.

Upvotes: 6

Related Questions