Here's a neat trick for factory/ classes. Say you have a class, ConnectionManager, that you want to be the only guy to instantiate a Connection class. Sure, sure, you can make the constructor package-private, but I'm not that trusting a guy. So...
public class Configuration
{
/** A constructor that ensures only ConfigurationManager can create configurations */
Configuration( ConfigurationManager.ConstructionParameters construct )
{
this.name = construct.name;
}
}
public final class ConfigurationManager
{
/** An small helper class that ensures only ConfigurationManager can instantiate Configuration */
static class ConstructionParameters
{
final String name;
private ConstructionParameters( String n ) { name = n; }
}
}
Okay, not that impressive. But now I know no-one is creating those Configurations except for my manager, even within this package.
|