Monday, December 11, 2017

Composite Pattern

Definition -
   
    It is a pattern used when you have objects of different functionalities and you want to build structures using these, but at the same time you want all the objects to be treated in a same way.
This pattern has three components to it -
1) Base components - It is the interface for all objects in the structure.
2) Leaf - one or more base components define a leaf. This is can be called as the building blocks of the structure.
3) Composite - it contains one or more leaf nodes.

Scenario -

    Let us take an example of the construction of a Building.
1) Base components - Make
2) Leaf - Walls, roof, doors, windows
3) Composite - Floor

Based on the above this is these are the classes which we will create
1. A abstract class called Make which have an build funtion.




package CompositePattern;

public abstract class make {
    
    public abstract void build();

}

2. There are leaf objects called walls, roof.

walls.java
 package CompositePattern;

public class walls extends make{

    @Override
    public void build() {
        
        System.out.println("Building walls");
        
    }

}


roof.java
 package CompositePattern;

public class roof extends make{

    @Override
    public void build() {
       
        System.out.println("Building roof");
       
    }

}



3. Construction is a composite object
package CompositePattern;

import java.util.ArrayList;

public class construction extends make{
    
    ArrayList<make> components= new ArrayList<make>();
    

    @Override
    public void build() {
        
        for(make structures: components) {
            structures.build();
        }
        
    }
    
    
    public void addstructure(make component) {
        components.add(component);
    }


}


4. To see the pattern in action use the below code

package CompositePattern;

public class compositepatterndemo {
    
    public static void main(String args[]) {
        
        make wls=new walls();
        make rf=new roof();
        
        construction ctr=new construction();
        ctr.addstructure(wls);
        ctr.addstructure(rf);
        
        ctr.build();
        
    }

}


Place to use -
1) When objects can be made into an hierarchy and the objects can treated in a similar fashion.

Place not to use -
1) When you do not want to make your objects too generic.
2) When you cannot create hierarchy and order objects in it.

To get the code for the above use the link
here


No comments:

Post a Comment