Monday, December 11, 2017

Decorator Pattern

Definition -

This pattern allows the designer to modify or extend the functionality of an object at run time. The speciality of this is that you can extend the capability of only one of the objects of the class.

Scenario -

    Let us take a scenario of manufacture of cars, the plant wants to modify various class for the same car depending on the order, which means some one might choose fullyloaded, basic and mid.

Based on the above this is these are the classes which we will create
1. An interface called as car. 

package DecoratorPattern;

public interface car {
    
    public void manufacture();

}

2. A basiccar class which will implement the interface car.
package DecoratorPattern;

public class basiccar implements car{

    @Override
    public void manufacture() {
        
        System.out.println("Maufacturing a basic car");
        
    }

}

3. A decorator class which implement car interface.
package DecoratorPattern;

public class decorator implements car {

    car cardemo;
    
    public decorator(car cars) {
        this.cardemo=cars;
    }
    
    @Override
    public void manufacture() {
        
        
        this.cardemo.manufacture();
        
        
    }

}

4. Two concrete decorators called fullyloaded and mid which will extend the decorator class.
fullyloaded.java
package DecoratorPattern;

public class fullyloaded extends decorator {

    public fullyloaded(car cars) {
        super(cars);
    }
    
    public void manufacture() {
        super.manufacture();
        System.out.println("Adding components of a fully loaded car");
    }

}


midlevel.java
package DecoratorPattern;

public class midlevel extends decorator {

    public midlevel(car cars) {
        super(cars);
    }
    
    public void manufacture() {
        super.manufacture();
        System.out.println("Adding components of a mid level car");
    }

}




We will first create a class called car1 and add engine and chassis as two components. Then we will clone this into car2 and display the components.

package DecoratorPattern;

public class decoratordemo {
    
    public static void main(String args[]) {
        
        car midlevelcar=new midlevel(new basiccar());
        midlevelcar.manufacture();
        
    }

}

 
Place to use -
1) When you deal with a system where if you go by normal design can create too much inheritence or sub classes.
2) You would want to add features / or modify an object in runtime.


To be careful about -
1) Since the features are added via decorators too many of these can cause maintainence issues.


The code used above can be found in the link here 



No comments:

Post a Comment