views:

624

answers:

4

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.

+1  A: 

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

frankodwyer
+7  A: 

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.

tcurdt
Java sure doesn't want me doing this. :P
Daddy Warbox
A: 

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.

tvanfosson
It's either that or end up with a God class.
Daddy Warbox
*shudder*. This is creative but insane!
Draemon
I agree, but it's not my requirement. :-)
tvanfosson
Yeah it's a mess. I'm still trying to wrap my brain around good practices, but my priority is still to get something out the door first and foremost.
Daddy Warbox
Works but *shudder*
tcurdt
A: 

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

Maurizio
I think that's a rather narrow if not naive view. Creational patterns have their place and factories are often good. IoC may have its place but it will never replace new.*Nothing* will ever be as clear or simple as A a = new A(); so it's preposterous to call it obsolete.
Draemon