Creating our own factory method in Java

Creating our own factory method in Java

Any factory method is created as a method belonging to an interface or abstract class. Hence that method is implemented, in the implementation classes or sub classes as case may be.

What are factory methods ?
A factory method is a method that creates and returns an object to the class to which it belongs. A single factory  method replaces several constructors in the class by accepting different options from the user , while creating the object.



For example, to create a factory method getFees() that will give the fees details for a course in an engineering college, we need to perform the following steps :

1> create an interface or abstract class
interface Fees {
   double showFees();
}

2>  Implement the abstract , public methods of the above interface.
class CSE implements Fees {
public double showFees(){
return 120000; // assumed some constant figure
}
}
// their can be more implementation classes also.

3> Create a factory class that contains factory method by the name getFees(). Mostly factory methods are written as static methods.
class CourseFees{
public static Fees getFees(String course){
if(course.equalsIgnoreCase("CSE"))
return new CSE();
else if(course.equalsIgnoreCase("ECE"))
return new ECE();
else return null;
}
}

// getFees() method takes the coursename from the user and creates an object either to CSE class or ECE class depending on the user option.

4> Call the factory method like this :
Fees f = CourseFees.getFees(name);

// In the preceding code, an object of CSE class or ECE class is returned by getFees() method. Since CSE and ECE are the implementation classes of Fees interface, we can use Fees interface reference 'f'  to refer to the objects of these classes. Hence, if we call f.showFees(), then the showFees() of that particular class either CSE or ECE will be executed and corresponding fees will be displayed.

// complete program : combining all 4 steps as above
import java.io.*;

interface Fees {
   double showFees();
}

class CSE implements Fees {
public double showFees(){
return 120000; // assumed some constant figure
}
}

class ECE implements Fees {
public double showFees(){
return 110000; // assumed some constant figure
}
}

class CourseFees{
public static Fees getFees(String course){
if(course.equalsIgnoreCase("CSE"))
return new CSE();
else if(course.equalsIgnoreCase("ECE"))
return new ECE();
else return null;
}
}

// using factory method
class Sctpl {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter course name");
String name = br.readLine();
Fees f = CourseFees.getFees(name);
System.out.println("The fees is Rs "+ f.showFees());
}
}

Comments

Popular posts from this blog

PPC - SomeOne SpenDing - SomeOne EarNing

Web scrapping tools,Sooo Muuch Data - Analysis Needed !

Must kNow Web Dev toolS - 2OI7