Design Pattern: Facade

Like the Adapter pattern, Facade is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities.

Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

The diagram definition of the Facade pattern is quite simple – all you’re really doing is insulating client from the subsystem:

So How Does It Work In Java?

Let’s put together a simple example in Java code to illustrate the pattern. Let’s take a travel agent site for example, that allows you to book hotels and flights.

We have a HotelBooker:

public class HotelBooker
{

  public ArrayList<Hotel> getHotelNamesFor(Date from, Date to) 
  {
      //returns hotels available in the particular date range

  }

}

And a FlightBooker:

public class FlightBooker
{

  public ArrayList<Flight> getFlightsFor(Date from, Date to) 
  {
      //returns flights available in the particular date range

  }

}

Both of these have Hotel and Flight datatypes, which the client has knowledge about. They could be provided in the same package as the Facade for example.

The TravelFacade class allows the user to get their Hotel and Flight information in one call:

 

public class TravelFacade
{

   private HotelBooker hotelBooker;
   private FlightBooker flightBooker; 

  public void getFlightsAndHotels(Date from, Data to)
  {
         ArrayList<Flight> flights = flightBooker.getFlightsFor(from, to);
         ArrayList<Hotel> hotels = hotelBooker.getHotelsFor(from, to);

         //process and return

   }

}

All that the client needs to worry about is the Facade class:

public class Client
{

   public static void main(String[] args)
   {
        TravelFacade facade = new TravelFacade(); 
        facade.getFlightsAndHotels(from, to);
   }
}

Downsides

By introducing the Facade into your code, you will be hardwiring subsystems into the Facade. This is fine if the subsystem never changes, but if it does, your Facade could be broken. Therefore, developers working on the subsystem should be made aware of any Facade around their code.

Adapter VS Facade

Similarity:

Like the adapter pattern, the Facade can be used to hide the inner workings of a third party library, or some legacy code.  All that the client needs to do is interact with the Facade, and not the subsystem that it is encompassing.

Difference:

Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one. Adapter and Facade are both wrappers; but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects.

Thanks to James Sugrue‘s artical: Design Patterns Uncovered: The Facade Pattern

FacebookTwitterGoogle+Share

Design Pattern: Adapter

The Adapter is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities.

Convert the interface of a class into another interface clients expect. Adapter helps two incompatible interfaces  to work together.

So How Does It Work In Java?

The following example shows a simple implementation of the pattern. Consider that we have a third party library that provides sorting functionality through it’s NumberSorter class. This is our Adaptee.

/* 
 * This is our adaptee, a third party implementation of a 
 * number sorter that deals with Lists, not arrays.
 */
public class NumberSorter
{
   public List<Integer> sort(List<Integer> numbers)
   {
      //sort and return
      return new ArrayList<Integer>();
   }

}

Our Client deals with primitive arrays rather than Lists. For the sake of this example, lets say we can’t change the client to use Lists. 

int[] numbers = new int[]{34, 2, 4, 12, 1};

Sorter sorter = new SortListAdapter();
sorter.sort(numbers);

We’ve provided a Sorter interface that expects the client input. This is our target.

//this is our Target interface
public interface Sorter
{
   public int[] sort(int[] numbers);
}

Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter

public class SortListAdapter implements Sorter
{

   @Override
   public int[] sort(int[] numbers)
   {
      //convert the array to a List
      List<Integer> numberList = new ArrayList<Integer>();
      
      //call the adapter 
      NumberSorter sorter = new NumberSorter();
      numberList = sorter.sort(numberList);
      
      //convert the list back to an array and return 
      
      return sortedNumbers;
   }
   
}

Downsides:

Some say that the Adapter pattern is just a fix for a badly designed system, which didn’t consider all possibilties. While this is a fair point, it is an important part of a pluggable architecture.  It can also add a level of complexity to your code, making debugging more difficult.

Design Pattern: Factory

For example a graphical application works with shapes.

Client: Drawing framework

Products: Different shapes

Abstract class/Interface: Shape class (The Shape class defines the draw and move operations which must be implemented by the concrete shapes.)

1. Client creates a new Circle

2. The framework receives the shape type as a string parameter, it asks the factory to create a new shape sending the parameter received from menu.

3. The factory creates a new circle and returns it to the framework, casted to an abstract shape.

4. Then the framework uses the object as casted to the abstract class without being aware of the concrete object type.

The advantage is obvious: New shapes can be added without changing a single line of code in the framework(the client code that uses the shapes from the factory).

//naive version

public abstract class Shape {
	public void draw();
}

public class Circle extends Shape{
	public void draw(){
		System.out.println("Draw a circle");
	}

}

public class Rectangle implements Product{
	public void getName(){
		System.out.println("Draw a rectangle");
	}
}

public class Factory {
	public Shape createProduct(String type){
		if(type.equals("Circle")){
			return new Circle();
		}
                if(type.equals("Rectangle")){
			return new Rectangle();
		}
                else
			return null;
	}
}

public class DrawingPanel{
        Factory f= new Factory();
	f.createProduct("Circle").draw();
	f.createProduct("Rectangle").draw();
}

The problem here is that once we add a new concrete product call we should modify the Factory class. It is not very flexible.

 

Design Pattern: Singleton

Sometimes it is important to have only one instance of a class. Singleton Pattern means that a class is responsible to instantiate itself, so that it can make sure it creates no more than one instance. In the same time, it should provide a global access to that instance.

*Something Important:

1. A static member in the “Singleton” class(Since the getInstance method is static, the instance should be static)

2. A private constructor (so that only the class itself can instantiate an instance)

3. A static public method that returns a reference to the static member

There are two main kinds of implementation of Singleton Pattern.

1. Lazy Instantiation

public class Singleton {
	private static Singleton instance = null;
	private Singleton(){

	}
	public static synchronized Singleton getInstance(){
		if(instance==null){
			instance = new Singleton();
		}
		return instance;
	}

        public void doSomething() {
		System.out.println("doSomething(): Singleton does something!");
	}

}

2. Early Instantiation

//Early instantiation using implementation with static field.
class Singleton {
	private static Singleton instance = new Singleton();

	private Singleton() {
		System.out.println("Singleton(): Initializing Instance");
	}

	public static Singleton getInstance() {
		return instance;
	}

	public void doSomething() {
		System.out.println("doSomething(): Singleton does something!");
	}
}

Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singleton. This techique has 2 drawbacks that makes singleton inheritance impractical:
1.  If the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
2. In order to use the derived class all the getInstance calls should be changed in the existing code from Singleton.getInstance() to NewSingleton.getInstance().