Pages

Wednesday, November 17, 2010

Design Patterns - Factory Method

A Factory method pattern (aka Factory pattern) is a creational pattern.

The creational patterns abstract the object instantiation process by hiding how the objects are created and make the system independent of the object creation process.

Factory pattern returns one of the several product subclasses. You should use a factory pattern If you have a super class and a number of subclasses,
and based on some data provided, you have to return the object of one of the subclasses.

Ex: Logger Factory, DAO Factory etc...


Usage:
  • When the system needs to be independent of how its products are created composed and represented.
  • When the system needs to be configured with one of multiple families of products.
  • When a family of products need to be used together and this constraint needs to be enforced.
  • When you need to provide a library of products, expose their interfaces not the implementation.

DAOFactory Example in detail:

If our project deals with different databases and getting the connection defers based on which database we would like to connect then DAOFactory is responsible for us the return appropriate sub class implementation based on the data we passed.

Here we will use the design principle of  "Code to an interface not to an implementation".

public interface DataSource() {
    Connection getConnection();
}

Different sub class implementations are like below:


public class OracleDataSource  implements DataSource {
    public Connection getConnection() {
        return new OracleConnection();
    }
}

public class AccessDataSource implements DataSource {
    public Connection getConnection() {
        return new AccessConnection();
    }
}

Now lets see how to create DAOFactory class:

public class DAOFactory {

    public static DataSource getDataSource(String databaseName) {
        if(databaseName == DataBaseEnum.Oracle {
            return new OracleDataSource();
        } else if(databaseName == DataBaseEnum.Access {
            return new AccessDataSource();
        }
    }
}

Now how the client looks like is:

public class TestDAO {
        
        public void retrieveTestData() {
            Connection con =   DAOFactory.getDataSource(DataBaseEnum.Oracle).getConnection();
            con.someMethod();
            ....
       }

}

Client code is independent of which subclass getting instantiated here.

This is a very simple example. This might not be used exactly in projects because we are now using Spring and all the dependencies like connections will be injected by Spring container and we are free of all those hassles.

But the same approach can be used in your business logic.

Happy Learning!

No comments:

Post a Comment