I have created factory class and i wonder which is better way to implement it.
option 1
public class Factory {
private IProperty prop;
public IDoc doc;
public Factory(int version) {
switch (version) {
case '1':
prop = new Prop();
doc = new Docu();
...
case '2':
prop = new Prop1();
doc = new Docu1();
...
}
}
public IProperty getProperty() {
return this.prop;
}
public IDoc getDoc() {
return this.doc;
}
}
My question is if to do it like that i.e. define member with the interface type and to to switch on the constructor or for every get method to use switch statement instead on the constructor, so in the constructor i will just get the
version and save it on class member and than for instance use like
public IProperty getProperty() {
switch (version) {
case '1':
prop = new Prop();
case '2':
prop = new Prop1();
...
So what is the better way, or any other idea?
First of all, your
Factoryshould ideally havestatic referencesinstead of
non-staticone. And it should have astatic methodto create / getthe appropriate instance.
Secondly, its better to have two different factories for different
types.
createProperty, rather thangetPropertyObject, because that method is not returning the alreadycreated instance, rather its creating one.
Of course,
getPropertyObject('1'), seems like it is fetching apropertyfor that version from a persistence storage, which is not what it is doing. It is rather creating an instance based on version.(NOTE: – Name of
static factory methodsare important. They are amongst one of the advantages, they have overconstructors. Since with aname, you can guess what exactly thatfactory methoddoes)Having said that, I would say, that the
2nd optionwould be better with all those changes. Let thecreatePropertymethod decide, how it wants to create theinstance.So, I would modify your code like this: –
Similarly, you can create a
DocumentFactoryto create adocument object. Name the method: –createDocument(char version)