The disadvantage of creating an object with the New keyword is that the coupling is too high, and the factory design pattern uses the Java reflection mechanism to instantiate the object to reduce the degree of coupling
PackageCn.buaa;Importjava.util.Date;Interfacefruit{ Public voideat ();}classAppleImplementsfruit{@Override Public voideat () {System.out.println ("Eat apples"); }}classOrangeImplementsfruit{@Override Public voideat () {System.out.println ("Eat oranges"); }}classfactory{ Public StaticFruit getinstance (String className) {Fruit F=NULL; Try{Class<?> CLA =Class.forName (className); F=(Fruit) cla.newinstance (); }Catch(Exception e) {e.printstacktrace (); } returnF; }} Public classHello { Public Static voidMain (string[] args)throwsException {Fruit f= Factory.getinstance ("Cn.buaa.Orange"); F.eat (); }}
Java Factory Design Patterns