Decrator Pattern

The definition of Decorator pattern (from Gang of 4) "Attach additional responsibilities to an object dynamically. Decorator provide a flexible alternative to sub classing for extending functionalities."

The classic example of decorator pattern is Java I/O package. We used to create a powerful reader by chaining file reader and buffered reader. So file reader got decorated by buffer reader at run time with out extending it.

BufferedReader buff = new BufferedReader(new FileReader("something.txt"));

Again back to our traditional Car example. Assume, Car came out of factory and it is ready for drive but not quite ready for fully operational. Because now Car directly going to a dealer and he/she needs to add their own accessories and some more accessories depends on customer choice. If we think about an object model here, we can clearly understand the decorator.

So Car manufacture has to create an interface ( assume an abstract class ) to satisfy both dealer specific accessories as well as customer specific ones, with out changing or extending car.Now dealer implementing all accessories by extending manufacture interface (abstract). Now dealer decided to create one more abstract class by extending manufacture interface, to give more choice to customers for highly customize the car.

//Manufacture abstract class
public abstract class Accessories {
public void addMoonRoof();
public void fixNumberPlate();
}

//Dealer concrete class
public class DealerAccessories extends Accessories {
public void addMoonRoof() { //add a basic moon roof }
public void fixNumberPlate(); { //fix number plate }
}

//Dealer abstract class for high customization
//allowing customer to choose what moon roof they want, panoramic, 3D etc
public abstract class AccessoriesDecorator extends Accessories {
public abstract void addMoonRoof();
public void fixNumberPlate(); { //fix number plate }
}

//Panoramic view moon roof
public class Panoramic extends AccessoriesDecorator {
public void addMoonRoof() { //add a panoramic moon roof }
public void fixNumberPlate(); { //fix number plate }
}

Now we have all in place, just we want to add it in car. Assume, car has one method called add Accessories(Accessories), here we can add any thing Panoramic or basic Dealer Accessories.

Comments

Popular posts from this blog

Coupon Crazy

Google's Killer Application.

Uncontrolled Musing