Javatpoint Logo

what is factory method?what is the use of that?

By: yogesh*** On: Fri Jun 07 16:32:58 EDT 2013     Question Reputation15 Answer Reputation0 Quiz Belt Series Points0  15Blank User
what is factory method?what is the use of that?Up0Down

 
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.
Image Created0Down

By: [email protected] On: Sat Jun 08 03:22:30 EDT 2013 Question Reputation0 Answer Reputation392 Belt Series Points0 392User Image
Are You Satisfied :2Yes1No