SYNOPFactory
and WRFFactory
are declared as inner class of DataFactory
.
It means that instances of them require a instance of DataFactory.
You could instantiate them for example as
Factory factory = new DataFactory().new WRFFactory();
But in fact, it makes not really sense to make them inner classes.
Why do you would need to couple so tightly instances of them with DataFactory
?
You should rather declare them in their own class file.
And extract also other classes in their own classes. Otherwise you would have the same problem.
Note that if you want to hide IDataSources
implementations from client, you could declare subclasses of them as private class member of the factory subclass that creates instances of them :
public class SYNOPFactory extends Factory {
private class SYNOP implements IDataSources {
}
@Override
public IDataSources CreateModel() {
return new SYNOP();
}
}
public class WRFFactory extends Factory {
private class WRF implements IDataSources {
}
@Override
public IDataSources CreateModel() {
return new WRF();
}
}
In this way, this will compile fine as you program by interface :
Factory factory = new WRFFactory();
IDataSources dateSources = factory.CreateModel();
But this will not as now WRF
is private to the WRFFactory
class :
WRF wrf = new ...;
Note also that it is not required to create multiple instances of a factory.
And repeating the new DataFactory()
idiom will finish by creating many factory instances.
A factory may create multiple instances of objects but why would you need to have multiple instances of a factory ?
A single one can create all objects you need.
So you should have a singleton instance of the factory.
To achieve it, you can use the singleton DP or the dependency injection (that is better).
Dependency injection requires a DI framework.
You don't seem to use it.
As workaround, in plain java, you could implement a eager Singleton (thanks Bill Pugh) such as :
public class WRFFactory extends Factory {
private class WRF implements IDataSources {
}
private static WRFFactory instance = new WRFFactory();
private WRFFactory(){
}
public static WRFFactory getInstance(){
return instance;
}
@Override
public IDataSources CreateModel() {
return new WRF();
}
}
Now, you can create your IDataSources
instances in this way :
IDataSources datasources = WRFFactory.getInstance().CreateModel();