Jump to content

Facade pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Arvindkumar.avinash (talk | contribs) at 07:50, 3 May 2006 (Java). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, a facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

  • make a software library easier to use and understand, since the facade 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 facade, thus allowing more flexibility in developing the system;
  • wrap a poorly designed collection of APIs with a single well-designed API.

The facade is an object-oriented design pattern.

Facades are very common in object-oriented design. For example, the Java standard library contains dozens of classes for parsing font files and rendering text into geometric outlines and ultimately into pixels. However, most Java programmers are unaware of these details, because the library also contains facade classes (Font and Graphics) that offer simple methods for the most common font-related operations.

Examples

Java

The output of the following example which hides parts of a complicate calendar API behind a more userfriendly facade is:

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

/** "Facade" */
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);
    }
}