Factory mode is the most common pattern for instantiating objects, which is used in place of the new operation. Creating an object in this mode will have some extra action, but it will bring greater scalability and less modification to the system. Typical application of the Spring bean container. Below is a simple example of implementing a factory.
1, animal interface, provide a common method body
Public Interface Animal { publicvoid eat ();}
2. Cat class, inherit animal interface, realize cat's Eat method
Public class Implements Animal { publicvoid eat () { System.out.println ("cat is eating ...");} }
3, dog, inherit the animal interface, realize the dog's Eat method
Public class Implements Animal { publicvoid eat () { System.out.println ("The Dog is eating ..." ); }}
4. Factory class
Note two points: 1) The return type is Interface 2) The instantiation of the class is implemented by reflection
Public classAnimalfactory { PublicAnimal getanimalbyclassname (String className) {Animal a=NULL; Try{a=(Animal) class.forname (className). newinstance (); } Catch(instantiationexception e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(ClassNotFoundException e) {e.printstacktrace (); } returnA; }}
5. Test class
Public class Model { publicstaticvoid main (string[] args) { new animalfactory (); = Af.getanimalbyclassname ("Design_pattern.factory.Cat"); A.eat (); = Af.getanimalbyclassname ("Design_pattern.factory.Dog"); A.eat (); }}
Java design mode (ii) Factory mode