Factory model is actually one of the most common modes in Java development. We often use factory models when getting database connections; Factory method decides which class; 3, applicability: a) When a class wants to specify the object it created by its subclass; b) When a class does not know what kind of object class you will create At the time (there are multiple object classes can be selected); c) When the class will create a responsibility of the object to a plurality of help subclauses, and what help subscribers you want to be the agent of the agent At the time; 4, Java implementation: factory class (Factory.java): Public class factory {public window createwindow (string type) {class cls = null; window win = null; try {cls = class.forname (Type); win = (Window) cls.newinstance ();} catch (exception ex) {ex.printstacktrace ();} return win;}
Public static void main (string [] args) {factory myfactory = new factory (); window mybigwindow = myfactory.createWindow ("Windowbig"); mybigwindow.func ();
Window mysmallWindow = myfactory.createWindow ("Windowsmall"); mysmallWindow.func ();}} --------------- Window interface (window.java) public abstract class window {public Abstract Class Window {public Void func ();} ---------------- The first Windowbig.java :public class windowbig extends window {public void func () {system.out. PRINTLN ("this is big window!");}} Two Sub-class in the second WindowsMall.java :public class windowsmall extends window {public void func () {system.out.println ("this is small window!" }}