A brief about Facade Design Pattern

Posted By : Mohit Shakya | 28-Feb-2018

  

In this blog, we'll get to know about 'Facade Design Pattern', a well-known Software Design Pattern for 'Object-oriented programming'.
 

We'll be covering following points in this:

  • Why we should use Facade Design Pattern
  • How to implement Facade Design Pattern ( An Example )

 

Why we should use Facade Design Pattern
Facade Design Pattern often used when we've to achieve following things:

  • When we need to use a bigger software libraries for some common tasks, then instead of the use of the whole library directly, it's better to make a Facade class that usage that library for common tasks and then using that 'Facade' class.
  • When we need to use multiple libraries for some common tasks in the application, it's better to use libraries using Facade class rather using them directly to avoid complex code. This also makes the code more readable.
  • When we need to use lesser dependencies for our own library than it's better to design a Facade class to perform all tasks that usage outside dependencies.
  • When we need to wrap a poorly designed code into well managed APIs.

 

How to implement Facade Design Pattern ( An Example )

Here's an example to achieve Facade Design Pattern.
In

this we'll use a Facade class that is dependent on Mail and Payment Gateway class to achieve payment mailing system.

 

class MailClass {  //class responsible for Mailing
	public MailClass(){
	}
	
	public void sendMail(String email, String template){
		System.out.println("Sending email to "+ email);
		//mailing code here ...
	}
}

class PGClass { // class responsible for Payment Gateway
	public PGClass(){
	}
	
	public boolean doPayment(int amount){
		boolean isPaid;
		String.out.println("Payment for amount: "+amount);
		// Payment code...
		return isPaid;
	}
}

class FacadeSystem { // wrapping both mailing and payment depencies into one class
	MailClass mail;
	PGClass pg;
	public FacadeSystem(){
		mail = new MailClass();
		pg = new PGClass();
	}
	
	public void doPayment(int amount, int email){
		if(pg.doPayment(amount)) {
			mail.sendMail( email, "Successful Payment" );
		}else{
			mail.sendMail( email, "Failed Payment" );
		}
	}
	
	public static void main( String[] args ){
		FacadeSystem system = new FacadeSystem();
		system.doPayment( 10, "[email protected]" );
	}
}

 

I hope you enjoyed the blog and this brief introduction to Facade Design Pattern will be helpful for you.

 

About Author

Author Image
Mohit Shakya

Mohit has worked in groovy and grails, filesystems, ffmpeg. Mohit likes to be adventurous, likes music, solving puzzles, playing chess, and basketball.

Request for Proposal

Name is required

Comment is required

Sending message..