Tuesday, January 26, 2010

Adapter Pattern

Adapter change the interface of a class to make is usable by client. Lets take a real world example....

Railways has got an interface to get the reservation details. Ex




A website which is doing well in ticket booking for flights want to introduce rail ticket booking as well. Since they are in business from long time, they have already got there generic interface in place for flight reservation.



My website TicketReservation class can't talk directly to RailReservation class. To make it happen we need some class which delegates all the calls make to isTicketAvalable to isRailTicketAvailable.



RailTicketAdapter is inherited form the client interface and composing RailTicketReservationImpl.

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();

}

Wednesday, January 13, 2010

Singleton pattern

Implies having at most single instance of a class.

Need:Singleton provides global way to access resources. Suppose we have a centralize configuration data to be used across the application, more than one instance of configuration data will result in incorrect behaviour of application. There are other examples as well when we need singleton mainly, thread pools, caches etc.

Ways to create:

class IAmSingleton{

private static IAmSingleton singletonRef;
public static IAmSingleton getInstance(){
if(singletonRef ==null)
return singletonRef = new IAmSingleton(); //line 1
else
return singletonRef ;
}
private IAmSingleton(){}
}

What if two threads are at line 1, two instances will be created. To stop this lets syncronize getInstance().
Synchronization come with cost of performance loss. Lets see how can we achieve single instance in multi threading environment with less impact.

If the object desired to behave as singleton is less resource incentive, we can go for pre loading the class(instance of class will be created at the class loading time).

class IAmSingleton{
private static IAmSingleton singletonRef = new IAmSingleton();
private IAmSingleton(){}
}

But if its resource incentive we can try to improve our synchronization logic. Lets see how..

class IAmSingleton{

private static volatile IAmSingleton singletonRef ;
public static IAmSingleton getInstance(){
if (singletonRef ==nulll)
syncronize (IAmSingleton.class){
if (singletonRef == null)
return new IAmSingleton();
else
return singletonRef ;
}
}
else
return singletonRef ;
}
privateIAmSingleton(){}

}

The advantage the above code will provide is, synchronized block will not be executed once value is assigned to singleton ref. This strategy is known as double check locking(double check locking doesn't work pre 1.5 JDK).

Sunday, January 10, 2010

Decorate your skills with Decorator pattern

To understand this pattern lets take a case.

Suppose a multiplex has a application to sell tickets. Now they want to sell tickets with different food/beverage option. We will try different design option one by one.

Option 1.
We sub class the base class and override the cost method. But that will result in class explosion(having lot of sub classes for each new functionality).
class MovieTicketPrice {

public double getTicketPrice(){

}
}

class MovieTicketWithCoke extends MovieTicketPrice {

public Double getTicketPrice(){
//modify the base class implementation here
}
}

but problem is we will have tons of subclasses(MovieTicketWithPopcorn, MovieTicketWithCokeAndPopcorn) of MovieTicketPrice corresponding to different options available.

Option 2.

We can have a single class and modify it

class MovieTicketPrice {
public double getTicketPrice(){}
public double addCokeSercharge(){}

}

But this design is violating basic design principle "Open for extension closed for modification". Its never a good idea to modify your already tested code to add new features.

Now lets see what we can achieve using decorator(wrapper ) pattern.

class MovieTicket{

public double getTicketPrice(){}

}

class DecoratePriceWithCoke extends MovieTicket{

MovieTicketPrice t ;
public double getTicketPrice(){
return t.getTicketPrice() + 50;
}
}

class DecoratePriceWithPopCorn extends MovieTicket{

MovieTicketPrice t ;
public double getTicketPrice(){
return t.getTicketPrice() + 80;
}
}

Now suppose we want to have an option of ticket with popcorn and coke, we don't need another class...just decorate(wrap) your movie ticket with coke and popcorn.

MovieTicket t = new MovieTicket();
t = DecoratePriceWithCoke(t);
t = DecoratePriceWithPopCorn(t);

To summerize you have to create a decorator class for new option and that can be mixed with other available option. for ex.. suppose multiplex introduce ticket with pizza. Then programmer just has to create pizza decorator class and the same can be mixed with options like pizza with coke without creating a new class PizzaWithCoke.