with - java interface factory method




In simplest terms, what is a factory? (4)

What is a factory and why would I want to use one?


What is a factory ?

Wikipedia explains in detail

Also see answer from legendary BalusC over here about many GoF patterns examples
In simple words Factory creates\initialize\allocate the objects that you can use in the code.
e.g if you have a person abstract class or interface or even a concrete class and you declare it in an other class e.g. private person; that is just that object has been declared but not created. You will either use new or some dependency injection or a factory to create this object (there are other options as well e.g Locator etc).

Why would I want to use one?

Now you might need to a have specific type of person e.g teacher or even person might have different implantation based of different configurations etc .Factory pattern takes care of this.It allows you or should I say frees you from worrying about what implementation or initialization of particular class should be used.



In simple terms, Factory is an OO design pattern that deals with creating objects without specifying the exact class of object that is to be created.

A good reason to use it is well defined in wikipedia:

The creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.


The Factory design pattern is ideal in circumstances when you need to create multiple instances of an object at run time. Rather than explicitly creating each instance you can initialize many instances. Additionally, you can encapsulate complex creation code that can be reused multiple times.

Example:

public class Person {
    int ID;
    String gender;
    public Person(int ID,String gender){
        this.ID=ID;
        this.gender=gender;
    }
    public int getID() {
        return ID;
    }
    public String getGender() {
        return gender;
    }
}
public class PersonFactory{
    public static Person createMale(int id){
        return new Person(id,"M");
    }
    public static Person createFemale(int id){
        return new Person(id,"F");
    }
}
public class factorytest{
    public static void main(String[]args){
        Person[] pList= new Person[100];
        for(int x=0;x<100;x++){
            pList[x]=PersonFactory.createMale(x);
        }
    }
}

In this example we encapsulate the details of the gender initialization parameter and can simply ask the PersonFactory to createMale or createFemale Person objects.





factory