Saturday, January 16, 2010

Factory patterns: A Quick Look

Factory patterns are mainly used to encapsulate creation of concrete object. These pattern facilitates adhering to design principle like: Inversion of control (Depend upon abstractions, Do not depend on concrete class), Program to interface not to implementation.

Simple factory: Suppose we want to create different concrete class based on different condition for ex.

class SellTicket {

Ticket t= new TicketCreationFactory().create("Bus");
t.sell();

}

class TicketCreationFactory {

public Ticket create(String type){

if(type.equals("Bus") return new BusTicket();
if(type.equals("Train") return new TrainTicket();

}
}

The advantage of having separate factory class would be reusability and maintainability. Different classes can use factory to create Tickets and we have got only one pace to modify for any change in object creation logic. But still we are violating some important design principle for ex. "Close for modification but open for extension"(to change object creation logic we have to modify factory class).

Factory method pattern: Factory method pattern provide an interface with abstract method to create object. By doing this it forces sub class to decide which class to instantiate. (Don't create instance in your interface delegate it to implementation)

abstract class SellTicket {

Ticket t = createTicket(String type) ;
t.sell();
public abstract Ticket createTicket(String type);

}

class sellTicketImpl extends SellTicket{

Ticket t = creatTicket() ;
t.sell();
public Ticket createTicket(String type){
if(type.equals("Bus")){
new BusTicket();
}
}

}

To have another object creation logic we can have another subclass of SellTicket.
Another interesting observation is our high level class SellTicket is not dependent on low level class ticket, instead it's dependent on abstract class Ticket. That's what know as "inversion of control" (Depend on abstraction, not on the concrete class). Lets explore it further, suppose we don't use abstract factory method
Ticket t = new BusTicket(); or Ticket t = new TrainTicket();
Though we have abstract class Ticket but our high level class is dependent on concrete implementation to create instance of class. By using factory method pattern we don't have to bother about change in class to be created or unknown classes to be added in future, because we have written our code that used interface not implementation.

Abstract Factory Pattern: Provides a interface for creating family of related objects without specify there concrete class.

Abstract factory pattern uses factory method pattern to create individual objects.

public interface TravelKitFactory{

public Ticket CreateTicket();
public WinterKit CreateWinterKit();

}

No comments:

Post a Comment