Factory Method Pattern

It is a factory of classes. when we have a super class (interface) and some subclasses and we have to return the object of one of the subclasses, we use a factory pattern.
Factory Method pattern recommends encapsulating the functionality required to select and instantiate an appropriate sub-class, inside a designated method referred to as a factory method.

Also known as: Virtual Constructor

One way of designing a factory method is to create an abstract class or an interface that declares the factory method or has a default implementation. Different subclasses of this can override the factory method to implement specialized factories. Factory often produces a hierarchy of creator classes that parallels the product class hierarchy.

The factory method can have a default implementation that returns a default concrete factory object. Also clients can directly call the factory method directly instead of always going through the creator.

Pay attention that the factory method returns the parent type.

Difference between Factory Method, Abstract Factory and Builder:
The factory is concerned with what is made, the builder with how it is made. Abstract factory is similar to builder in that it too may construct complex objects but Builder pattern focuses on constructing a complex object step by step through difference method calls. Abstract factor's emphasis is on families of product objects (either simple or complex). Builder returns the product as the final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

factory.jpg
public interface Product {
}
 
public class AdslProduct implements Product {
}
 
public class DialProduct implements Product {
}
 
public class ProductFactory{
 
    //this condition can be set in runtime or through a config file, etc.
    private boolean condition;
 
    public Product getProduct(){
        if(condition) return new AdslProduct();
        else return new DialProduct();
    }
 
    public void setCondition( boolean cond){
        this.condition = cond;
    }
}
 
public class Client {
    public static void main(String[] args) {
        ProductFactory factory = new ProductFactory();
        Product p = factory.getProduct();
    }
}

A concrete factory for every concrete product above:

public interface ProductFactory {
    public Product getProduct();
}
 
public class AdslProductFactory implements ProductFactory {
    @Override
    public Product getProduct() {
        //
    }
}
 
public class DialProductFactory implements ProductFactory{
    public Product getProduct(){
        //implement the factory method
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License