Factory means a location where things are manufactured. Any method which would be creating object of certain classes automatically by itself and wound be returning the required objects to our program could be called as the factory method.
Usually a factory method could be creating objects of the classes by executing private constructor or by calling the native methods and returns the required objects to our programs. So that our programming become simple & easy.
A factory method would be always public & static.
Sometimes the factory method could be also return the object of the same classes by executing the private constructor of the same classes.
Ex :
public class MyFactory
{
private MyFactory myObject;
private MyFactory(){
System.out.println("This private constructor");
}
public MyFactory getMyFactory(){
try{
myObject = new MyFactory();
System.out.println("Creating object:"+myObject);
}catch(Exception e){
e.printStackTrace();
}
return myObject;
}
}
private MyFactory(){
System.out.println("This private constructor");
}
public MyFactory getMyFactory(){
try{
myObject = new MyFactory();
System.out.println("Creating object:"+myObject);
}catch(Exception e){
e.printStackTrace();
}
return myObject;
}
}
public class FactoryTest {
public static void main(String[] args) {
MyFactory myfact = MyFactory.getMyFactory();
System.out.println("Object :"+myfact);
}
}
No comments:
Post a Comment
Please share your feedback