Question

My problem is thus: I need a way to ensure only one given class can instantiate another. I don't want to have to make the other a nested inner class or something dumb like that. How do I do this? I forget offhand.

Was it helpful?

Solution

Make the constructor private. Create a static factory method that takes an instance of the class that is allowed access. Have the factory method create a suitable object and use a settor on the object that is allowed access to the created object to give that class the created copy.

public class AllowedAccess
{
    private SecureClass secure;
    public setSecureClass( SecureClass secure )
    {
        this.secure = secure;
    }

    ...
}

public class SecureClass
{
     private SecureClass() {}

     public static void Create( AllowedAccess allowed )
     {
          allowed.setSecureClass( new SecureClass() );
     }

     ...
}

BTW, I'm suspicious of this design. Seems too highly coupled to me.

OTHER TIPS

A private static inner class is exactly what you want. Nothing dumb about it.

public class Creator {
  private static class Created {
  }
}

Otherwise you can only protect instantiation on the package level.

public class Created {
  Created() {
  }
}

Which gives only classes from the same package access to the constructor.

You could make the class that is to be protected from instantiation package private.

I agree with tvanfosson's answer and also with his comment about too high coupling. Why don't you retain more control of you class creation process by adopting an Inversion of Control framework like Spring or Guice?

IMHO creating classes with the "new" statement is to be considered a bit... obsolete, factories are to be preferred and IoC frameworks even more.

Regards

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top