Façade pattern

From Wikipedia, the free encyclopedia

The façade pattern is an object-oriented design pattern. A façade is an object that provides a simplified interface to a larger body of code, such as a class library. A façade can:

  • make a software library easier to use and understand, since the façade has convenient methods for common tasks;
  • make code that uses the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the façade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API.


[edit] Examples

[edit] Java

The following example hides the parts of a complicated calendar API behind a more userfriendly façade. The output is:

Date: 1980-08-20
20 days after: 1980-09-09
import java.util.*;

/** "Façade" */
class UserfriendlyDate 
{
    GregorianCalendar gcal;
     
    public UserfriendlyDate(String isodate_ymd) {
        String[] a = isodate_ymd.split("-");
        gcal = new GregorianCalendar(Integer.valueOf(a[0]).intValue(),
              Integer.valueOf(a[1]).intValue()-1 /* !!! */, Integer.valueOf(a[2]).intValue());
    }
    public void addDays(int days) { gcal.add(Calendar.DAY_OF_MONTH, days); }
    public String toString() { return new Formatter().format("%1$tY-%1$tm-%1$td", gcal).toString();}
}

/** "Client" */
class FacadePattern 
{
    public static void main(String[] args) 
    {  
        UserfriendlyDate d = new UserfriendlyDate("1980-08-20");   
        System.out.println("Date: "+d);   
        d.addDays(20);   
        System.out.println("20 days after: "+d);
    }
}

[edit] External links