Monday, 9 February 2015

Background

Some time back we saw Decorator design pattern which was the 1st Structural design pattern that we tried to understand. Adapter and Facade are two more design pattern that come under same category - Structural Design pattern.

Adapter Design Pattern

Adapter pattern converts one interface to another interface that is expected by the target or client system. It simply make interfaces compatible so that integration is possible. To visualize see following diagram

Target or client expects an interface where as interface that is going to use it provides different interface and none of them can be modified. In such cases Adapter proves to be beneficial.

Lets take an example -

Lets say you have designed a program that computes cost of a list of items supplied to it. In your computeCost() method you expect that customer would provide Iterator instance. You write code something like below -

Also you have exposed a Product interface. Those who want to compute cost should have models extending this Product interface implement it's getCost() method and then can pass the iterator of it to above utility method.

public interface Product {
int getCost();
}

Now here's something you did not expect. You get a Toy manufacturing company as your client and their code is something like -

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method computeCost(Iterator<Product>) in the type CostComputer is not applicable for the arguments (Enumeration) at ToysCostComputer.main(ToysCostComputer.java:6)

Program crashed. Your code expected a Iterator but customer code returns Enumeration. Now you or your customer have to build Adapter to support Enumeration.

so in facade pattern Adapter implements target and has an instance of Adaptee. So whenever methods of target are called we call suitable methods of adaptee.

Facade Pattern.

Facade Pattern is kind of an overlay. It provides a unified interface to set of interfaces in the sub system. Note that we cannot say it encapsulates methods of sub system classes as methods of sub system classes are still available for direct use. Facade pattern just simplifies it by abstraction.

There is no fixed generic class diagram as such but it will look like -

class BugsReplicator that tries replicates the bug as per the description of filed bug.

Methods : replicateBug(Bug newBug) etc

class BugsSolver that finds the fix and checks in the code.

Methods : fixBug(Bug newBug) etc

class BugsDeployer thatdeploys the fix to dev or qa environments.

Methods : deployFix(CodeFix fix) etc

class BugsTester that tests out the fix

Methods : testFix(Bug bug) etc

Now lets say your customer uses these classes or subsystems to handle their code bugs. They will have to call each method and do handling on their own. Instead you can provide them with a simplified facade.