Refactoring
What approach is better and effective:
publicstatic ClientFramework getInstance()
{
if (instanceObj ==null)
{
instanceObj =new ClientFramework();
}
return instanceObj;
}
publicstatic ClientFramework getInstance(Log logger)
{
if(instanceObj ==null)
{
instanceObj =new ClientFramework();
}
instanceObj.setLogger(logger);
return instanceObj;
}
or
publicstatic ClientFramework getInstance()
{
instanceCheckMethod();
return instanceObj;
}
publicstatic ClientFramework getInstance(Log logger)
{
instanceCheckMethod();
instanceObj.setLogger(logger);
return instanceObj;
}
privatevoid instanceCheckMethod(){
if (instanceObj ==null)
{
instanceObj =new ClientFramework();
}
}
public static ClientFramework getInstance()
{
return getInstanceObj(DEFAULT_LOGGER);
}
public static ClientFramework getInstance(Log logger)
{
createClientFrameworkIfNecessary();
clientFramework.setLogger(logger);
return clientFramework;
}
private void instanceCheckMethod() {
if (clientFramework == null)
{
clientFramework = new ClientFramework();
}
}
~
well, what benefits do you see with the second example?in both instances, you have some repeated code: the check for null, followed by creation. factor that repetition out by having the getInstance(Log logger) method get it's ClientFramework from the first method.
public static ClientFramework getInstance()
{
return getInstance(new Log());
}
public static synchronized ClientFramework getInstance(Log logger)
{
if(instanceObj == null){
instanceObj = new ClientFramework();
instanceObj.setLogger(logger);
}
return instanceObj;
}
Would be my suggestion. Depending on what's supposed to happen with the logger.