Friday, May 24, 2013

Design Pattern: Facade

 Let's say that I want to make a pb&j sandwich. I have bread, peanut butter and jelly. Now I can take two slices of bread, put peanut butter on one slice and jelly on the other. Then I can put the two slices together. Great.

Now let's look at how we might do this in code. Here we have some PBJ sandwich related classes.
 public class PeanutButter implements Spreadable{  
 public class Jelly implements Spreadable{  
 public class Bread{  
 public class Knife {...}  
 public class Jar{ ...}  

So a client could make a sandwich like so:
 public static void main(String[] args) {  
     Bread slice1 = new Bread();  
     Bread slice2 = new Bread();  
     PeanutButter pb = new PeanutButter();  
     Jelly jelly = new Jelly();  

But thats a little too detailed for me. I don't care about all the complexities. As a client, all I know is that I am hungry and want a sandwich. So let's provide a facade:
 public class PBJSandwich(){  
   public void make();  
 public static void main(String[] args) {  
    PBJSandwich sandwich = new PBJSandwich();  
The make method is a facade because it hides underlying complexities and provides a simplified interface for the client.