The Facade Design Pattern (II)

9 March 2008

This post is in continuation of The Facade Design Pattern (I). Do read that before this one.

Structure of the Facade Design Pattern

Facade: It hides the parts of a complicated API behind a more easy to understand and user friendly facade. The facade class interacts with different Packages with the rest of the application.

Clients: The objects using the Facade Pattern to access resources from the Packages.

Packages: Software library or API collection are accessed through the Facade Class.

The example below demonstrates use of facade design pattern. If you want to add a few days to a date, you would require to use a complicated calendar API with not that easy to understand code. With the help of facade design pattern you can write easy to understand and easy to use methods to add days you want to a date.

import java.text.*;
import java.util.*;
 
// This is is facade
class MyFacadeDate
{
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 
    public MyFacadeDate (String isodate_ymd) throws ParseException {
        Date date = sdf.parse(isodate_ymd);
        cal.setTime(date);
    }
 
    public void addDays (int days) {
        cal.add (Calendar. DAY_OF_MONTH, days); 
    }
 
    public String toString() { 
        return sdf.format(cal.getTime()); 
    }
}
 
// This is a client
class FacadeDemo
{
    public static void main(String[] args) throws ParseException
    {  
        MyFacadeDate d = new MyFacadeDate("2005-09-03");   
        System.out.println ("Date: " + d.toString());   
        d.addDays(20);   
        System.out.println ("20 days after: " + d.toString());
    }
}

Output:
Date: 2005-09-03
20 days after: 2005-09-23

del.icio.us:The Facade Design Pattern (II)  digg:The Facade Design Pattern (II)  spurl:The Facade Design Pattern (II)  wists:The Facade Design Pattern (II)  simpy:The Facade Design Pattern (II)  newsvine:The Facade Design Pattern (II)  blinklist:The Facade Design Pattern (II)  furl:The Facade Design Pattern (II)  reddit:The Facade Design Pattern (II)  fark:The Facade Design Pattern (II)  blogmarks:The Facade Design Pattern (II)  Y!:The Facade Design Pattern (II)  smarking:The Facade Design Pattern (II)  magnolia:The Facade Design Pattern (II)  segnalo:The Facade Design Pattern (II)  gifttagging:The Facade Design Pattern (II)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: The Facade Design Pattern (II)

Leave a Reply