Monday, December 11, 2017

Facade Pattern


Definition -

    This provides a standard interface for all the interfaces in the system or sub system.   

Scenario -

    Let us take an example of building a house, the components walls, roof needs to come together in order to complete it. If you would approach to start this without the pattern then you would have to handle too many scenarios to ensure the classes are called in particular order. The facade pattern is used to make the job easier.
   
Based on the above scenario -
1) A class called walls which will build all the walls.

package FacadePattern;

public class walls {
    
    public void buildwalls() {
        System.out.println("Building walls");
    }


}

2) A class called roof which will build the roof.
package FacadePattern;

public class roofs {
    
    public void buildroofs() {
        System.out.println("Building roofs");
    }

}

3) A class called housefacade which will take care of the calling a class by the interface instead of calling roof and walls separately.
 
package FacadePattern;

public class housefacade {
    
    private walls wall=new walls();
    private roofs roof=new roofs();
    
    public void build() {
        wall.buildwalls();
        roof.buildroofs();
    }

}

4) To see the pattern in action use the code below 
package FacadePattern;

public class facadedemo {
    
    public static void main(String args[]) {
        
        housefacade house=new housefacade();
        house.build();
        
    }
    
}


Place to use -
1) Use this when you have too many interfaces and you want to simplify the interaction with the client.
2) People generally use this while building web services since a single web services will have multiple methods. 


The source for the above can be found in the link here



No comments:

Post a Comment