Defines an interface for creating an object, but let subclasses decide which class to instantiate.

The Factory Method is a simple way of making a design more customizable. It automates object creation and allows increased modularization which makes the application more extensible.

More information about this Design Pattern can be obtained from Design Patterns by GoF (Gang of Four). The Factory Method is closely related to the Abstract Factory Pattern, which has a stronger focus on class Families.

An example of when to use the Factory Pattern is when you want to return instances of different classes depending on what argument you give the factory. An example is when you want to calculate the area of a circle or square.

Define a primitive class that holds the area:

class Primitive
{
    double area = 0;

    public double getArea(  )
    {
        return area;
    }
}

Define the square and circle class, extending Primitive:

class Square
    extends Primitive
{
    Square( 
        double width,
        double height )
    {
        area = width * height;
    }
}
class Circle
    extends Primitive
{
    public Circle( double radius )
    {
        area = radius * radius * Math.PI;
    }
}

And the factory that instantiate the different primitives depending on the arguments

class PrimitiveFactory
{
    Primitive getPrimitive( String s )
    {
        int split = s.indexOf( '*' );

        if ( split == -1 )
        {
            return new Circle( Integer.parseInt( s ) );
        }
        else
        {
            return new Square( Integer.parseInt( s.substring( 0, split ) ), 
                               Integer.parseInt( s.substring( split + 1 ) ) );
        }
    }

And this is how you would use it:

PrimitiveFactory factory = new PrimitiveFactory(  );

System.out.println("Circle area: "+ factory.getPrimitive("15").getArea() );
System.out.println("Square area: "+ factory.getPrimitive("15*15").getArea() );        

Log in or register to write something here or to contact authors.