In addition to the methods mentioned above, you can use the reflection mechanism of Java so that the class name can be used to load the required classes. We just need to change the factory class and drive class.
Fruitfactory.java
PackageCom.muggle.project;//Fruit Factory Public classFruitfactory { Publicfruitinterface getfruit (String key) {if("Banana". Equals (Key) { return NewBanana (); } Else if("Apple". Equals (Key) { return NewApple (); } Else { return NULL; } } /*to create an object using the class name*/ Publicfruitinterface Getfruitbyclass (String calssname) {Try{fruitinterface Fruit=(Fruitinterface) class.forname (calssname). newinstance (); returnfruit; } Catch(Instantiationexception | illegalaccessexception |classnotfoundexception e) { //TODO auto-generated Catch blockE.printstacktrace (); } return NULL; }}
Using a dynamically loaded method, you can create an object directly with the class name.
Testdrive.java
PackageCom.muggle.project; Public classtestdrive { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub /*the original method without Factory mode*///fruitinterface banana=new Banana ();//banana.produce ();//fruitinterface apple=new Apple ();//apple.produce (); /*the original method of using Factory mode*///fruitfactory Factory =new fruitfactory ();//fruitinterface banana=factory.getfruit ("banana");//banana.produce ();Fruitfactory Factory=Newfruitfactory (); Fruitinterface Banana=factory.getfruitbyclass ("Com.muggle.project.Banana"); Banana.produce (); }}
Factory mode for Java (ii)