Quick Java question: Creating an instance of this class from just another?

My problem is this: I need a way to ensure that only one given class can instantiate another. I don't want the other to be a nested inner class or something so stupid. How can I do it? I forget about him.

+4
source share
4 answers

Make the constructor private. Create a static factory method that takes an instance of a class that is allowed access. Ask the factory method to create a suitable object and use the installer on the object that is allowed access to the created object to give this class a 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() ); } ... } 

By the way, I am suspicious of this design. I seem to be too attached to me.

+1
source

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

 public class Creator { private static class Created { } } 

Otherwise, you can protect the instance only at the package level.

 public class Created { Created() { } } 

This only gives classes from the same constructor access package.

+8
source

You can make a class that should be protected from a private instance package.

+1
source

I agree with tvanfosson's answer, as well as his comment on too high grip. Why don't you maintain control over the process of creating your class by adopting Inversion of Control , such as Spring or Guice ?

IMHO, creating classes with a "new" operator should be considered a bit ... obsolete, factories should be preferable and IoC frameworks even more.

Hello

-2
source

All Articles