Saturday, 19 July 2014

Decorator Design pattern

Decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Lets take an example, where a company offer services to decorate your home.
Below decorating styles are offered.

a. Decorating with Natural Flowers


b. Decorating with Artificial Flowers


c. Decorating with lights.


d. Decorating with combinations of a, b or c.

interface Decorator {
    void draw();
}

public final class NaturalFlowersDecorate implements Decorator{
    
    Decorator decor;
   
    @Override
    public void draw(){
        if(decor != null){
            decor.draw();
        }
        System.out.println("Decorating with Natural flowers");
    }
    
    NaturalFlowersDecorate(){
        
    }
    
    NaturalFlowersDecorate(Decorator decor){
        this.decor = decor;
    }
}

public class ArtifitialFlowerDecorate implements Decorator{
    Decorator decor;
    
    ArtifitialFlowerDecorate(){
        
    }
    
    @Override
    public void draw(){
        if(decor != null){
            decor.draw();
        }
        System.out.println("Decorating with Artifitial flowers");
    }
    
    ArtifitialFlowerDecorate(Decorator decor){
        this.decor = decor;
    }
}

public class LightsDecorate implements Decorator{
    Decorator decor;
   
    LightsDecorate(){
        
    }
    
   @Override
    public void draw(){
        if(decor != null){
            decor.draw();
        }
        System.out.println("Decorating with lights");
    }
    
    LightsDecorate(Decorator decor){
        this.decor = decor;
    }
}

public class TestDecorator{
    public static void main(String args[]){
        LightsDecorate lightDec;
        lightDec = new LightsDecorate(new NaturalFlowersDecorate(new ArtifitialFlowerDecorate()));
        lightDec.draw();
    }
}

Output
Decorating with Artifitial flowers
Decorating with Natural flowers
Decorating with lights



                                                             Home

No comments:

Post a Comment