Factory method is a method that returns the instance of the class. For example, class A{ public static A getA(){ return new A(); } } This is the simple example of factory method. Factory method can be used in two cases: 1) It can be used to return the singleton object. 2) It can be used to return the unknown object. Suppose I want to create the database connection object only once, and reuse it in all the programs, I will write: import java.sql.*; class ConnectionProvider{ private static Connection con=null; private ConnectionProvider(){} static{ try{ Class.forName(\"oracle.jdbc.driver.OracleDriver\"); con=DriverManager.getConnection(\"jdbc:oracle:thin:@localhost:1521:xe\",\"system\",\"oracle\"); }catch(Exception){e.printStackTrace();} } public static Connection getConnection(){ return con; } } Now you may get the Connection object by calling. Connection con=ConnectionProvider.getConnection(); A factory method can be static and non-static both. It can be used to return the instance of its own class or another class. | 0 |
By: [email protected] On: Sat Jun 08 03:22:30 EDT 2013 0 392 0 | 392 |
Are You Satisfied :2Yes1No |