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?
getPropertymethod decide how it builds theproperty.IProperty/IDocinstances returned by the same instance ofFactorywill always be the same, while in 2nd case there is still a possibility to change instances returned byFactoryinstance during it's lifetime. Though presence ofswitchstatement clearly indicates that polymorphism can (and actually should) be used instead of it - please refer tobobahanswer which describes how it is done.