Tuesday 8 June 2010

Factory Pattern

Factory Pattern:
sometimes, an Application (or framework) at runtime, can not anticipate (getting) the class of object that it must create
The application (or. framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it can not instantiate. Thus the application class may only know when it has to instantiate a new object of a class, not what kind of subclass to create.

Hence a class may want it's subclasses to specify the objects to be created.

The factory pattern design pattern handles these problems by defining a separate method for creating the objects, these methods optionally accept parameters defining how the object is created, and then return the created object.

Problem:

Creating multiple objects for multiple subclasses and utilizing one of them based on the supplied data is wrong methodology because the remaining objects became unnecessarily created objects.

Solutions:
use Factory Pattern, here the method of super class or some other class instantiates/creates one of the several sub classes objects based on the supplied data provided by user (at compile time/ at run time) that means objects for remaining sub classes will not be created.

Def:
  Define an interface for creating an object, but let the sub classes decide which class to instantiate. The Factory Method lets a class defer instantiation to sub classes.
 A Simple Factory pattern return an instance of one of several possible (sub) classes depending on the data provided to it. Usually all classes that it returns have a common parent class and common methods, but each performs a task differently and is optimized for different kinds of data.

Intent:

  •  creates objects without exposing the instantiation logic to the client.
  • Refers to the newly created object through a common interface
Application Areas:


  • A class can not anticipate the class of objects it must create.
  • A class specifies its sub-classes to specify which objects to create.
  • In programmer's language, you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.
Ex:

In JDBC APPLICATIONS , DriverManager.getConnection(-,-,-) method logic is nothing but factory pattern logic because based on the argument values that are supplied, it creates and returns one of the JDBC driver class that implements the java.sql.Connection interface.

  1. Connection con=DriverManager.getConnection("jdbc.odbc:rajendra","uname","pwd");
  • here getConnection() call returns the object of Type-1 JDBC DRIVER class. 





Factory Method

No comments:

Post a Comment