Monday 14 November 2016

Title

Decorator Pattern

Decoration means putting things on or around an entity to make it look more appealing or attractive. This design pattern tries to add more functionality to an object at runtime without having to modify the object itself.

Let’s consider Juice Center, where different kinds of Fruit Juices are made available. Price depends on the Kind of Fruit used for the preparation of Juice. Vendor realizes over a period of time that by adding different toppings like Honey or Dry Fruits he could increase the price of the Juice itself.

enter image description here

Written with StackEdit.

interface FruitJuice {
    void prepare();
    int getPrice();
}

class AppleJuice implements FruitJuice {

    @Override
    public void prepare() {
        System.out.println("Prepare Apple Juice");

    }
    @Override
    public int getPrice() {

        return 10;
    }
}

class OrangeJuice implements FruitJuice {
    @Override
    public void prepare() {
        System.out.println("Prepare Orange Juice");
    }
    @Override
    public int getPrice() {
        return 10;
    }
}

Orange Juice and Apple Juice are the two kind of Juice available at the Juice Center.

abstract class JuiceDecorator implements FruitJuice {

    protected FruitJuice juice;

    JuiceDecorator(FruitJuice fruitJuice) {
        this.juice = fruitJuice;
    }

    public void prepare() {
        this.juice.prepare();
        this.decorate();

    }

    public int getPrice() {

        return juice.getPrice() + this.addCost();
    }

    abstract void decorate();

    abstract int addCost();

}

class HoneyDecorator extends JuiceDecorator {

    HoneyDecorator(FruitJuice fruitJuice) {
        super(fruitJuice);
    }

    @Override
    void decorate() {
        System.out.println("Decorate with Honey");

    }

    @Override
    int addCost() {

        return 5;
    }

}

class DryFruitDecorator extends JuiceDecorator {

    DryFruitDecorator(FruitJuice fruitJuice) {
        super(fruitJuice);
    }

    @Override
    void decorate() {
        System.out.println("Decorate with Dry Fruits");

    }

    @Override
    int addCost() {

        return 30;
    }

}

Two Kinds of Decorators are added , each of these decorators extend from the abstract JuiceDecorator class. It implements the methods decorate() and addCost() which adds the appropriate topping and increases the cost according to the toppings added.


public class DecoratorDemo {

    public static void main(String[] args) {
        FruitJuice appleJuice = new AppleJuice();
        appleJuice.prepare();
        System.out.println("Apple Juice Price : " + appleJuice.getPrice());

        FruitJuice orangeJuice = new OrangeJuice();
        orangeJuice.prepare();
        System.out.println("Orange Juice Price : " + orangeJuice.getPrice());

        FruitJuice honeyDecoratedAppleJuice = new HoneyDecorator(appleJuice);
        honeyDecoratedAppleJuice.prepare();
        System.out.println("Apple Juice with Honey Price : "
                + honeyDecoratedAppleJuice.getPrice());

        FruitJuice dryFruitDecoratedOrangeJuice = new DryFruitDecorator(
                orangeJuice);
        dryFruitDecoratedOrangeJuice.prepare();
        System.out.println("Orange Juice with Dry Fruits Price : "
                + dryFruitDecoratedOrangeJuice.getPrice());

    }

}

Output

Prepare Apple Juice
Apple Juice Price : 10
Prepare Orange Juice
Orange Juice Price : 10
Prepare Apple Juice
Decorate with Honey
Apple Juice with Honey Price : 15
Prepare Orange Juice
Decorate with Dry Fruits
Orange Juice with Dry Fruits Price : 40

Friday 11 November 2016

Iterator Pattern

Iterator Pattern - Behavioral

Pattern primarily used when you want to traverse a collection in a particular order. It helps to separate the algorithm for traversing the collection from the data structure that represents the collection.
enter image description here
Let’s try to understand with an example. We have a collection that stores all the US Presidents till 2016. Suppose we need to traverse this collection in Chronological Order (in the order in which they held the Presidency) and also in Alphabetical Order(as per the name).
Instead putting all the logic to traverse in the data model (collection), we make use of the Iterator pattern.
interface Iterator {
    String next();
    boolean hasNext();
}
Define, an Interface(Iterator) that provides two methods.
- next() - next name in the collection
- hasNext() - returns true if there are more elements.
We, would be creating two Iterators implementing the above interface, one for each kind of traversal.
interface CollectionInterface {
    Iterator getChronologicalIterator();
    Iterator getAlphabecticalIterator();
}

class Collection implements CollectionInterface {
    String[] listOfUSPresidents = { "George Washington", "John Adams", "Thomas Jefferson", "James Madison",
            "James Monroe", "John Quincy Adams", "Andrew Jackson", "Martin Van Buren ", "William Henry Harrison",
            "John Tyler", "James K. Polk", "Zachary Taylor", "Millard Fillmore", "Franklin Pierce", "James Buchanan",
            "Abraham Lincoln", "Andrew Johnson", "Ulysses S. Grant", "Rutherford B. Hayes", "James A. Garfield",
            "Chester A. Arthur", "Grover Cleveland", "Benjamin Harrison", "Grover Cleveland", "William McKinley",
            "Theodore Roosevelt", "William Howard Taft", "Woodrow Wilson", "Warren G. Harding", "Calvin Coolidge",
            "Herbert Hoover", "Franklin Roosevelt", "Harry S. Truman", "Dwight D. Eisenhower", "John F. Kennedy",
            "Lyndon B. Johnson", "Richard M. Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George Bush",
            "Bill Clinton", "George W. Bush", "Barack Obama", };

    @Override
    public Iterator getChronologicalIterator() {

        return new Iterator(){
            int index =0;
            @Override
            public String next() {
                 if(this.hasNext()){
                        return listOfUSPresidents[index++];
                     }
                     return null;
            }

            @Override
            public boolean hasNext() {
             if(index < listOfUSPresidents.length){
                    return true;
                 }
                 return false;
            }

        };
    }


    @Override
    public Iterator getAlphabecticalIterator() {

        return new Iterator(){
            int index =0;
            String []sortedList = getSortedList(listOfUSPresidents);

            @Override
            public String next() {
                 if(this.hasNext()){
                        return sortedList[index++];
                     }
                     return null;
            }

            @Override
            public boolean hasNext() {
             if(index < sortedList.length){
                    return true;
                 }
                 return false;
            }

            String [] getSortedList(String []names){
                String [] sortedList = names;
                Arrays.sort(sortedList);
                return sortedList;
            }

        };
    }
}
Collection stores the list of Presidents, We have two implementations of the Iterators, one representing the chronological order(same as the model), the other iterator internally sorts the list of names to provide alphabetically order.

Key Points

  1. Traverse a collection of Objects(Model) without proliferating the traversing logic inside the collection object.
  2. Provide multiple strategies/algorithms for traversing the same collection/model.
public class IteratorDemo {

    public static void main(String[] args) {
        Collection collection = new Collection();
        // Chronological Iterator
        System.out.println("List of Presidents in Chronolgical Order");
        Iterator chronoIterator = collection.getChronologicalIterator();
        while (chronoIterator.hasNext()) {
            System.out.println(chronoIterator.next());
        }

        // Alphabetical Iterator
        System.out.println("List of Presidents in Aphabetical Order");
        Iterator alhabaItetrator = collection.getAlphabecticalIterator();
        while (alhabaItetrator.hasNext()) {
            System.out.println(alhabaItetrator.next());
        }
    }

}

Output : List of US Presidents

List of Presidents in Chronolgical Order
George Washington
John Adams
Thomas Jefferson
James Madison
James Monroe
John Quincy Adams
Andrew Jackson
Martin Van Buren 
William Henry Harrison
John Tyler
James K. Polk
Zachary Taylor
Millard Fillmore
Franklin Pierce
James Buchanan
Abraham Lincoln
Andrew Johnson
Ulysses S. Grant
Rutherford B. Hayes
James A. Garfield
Chester A. Arthur
Grover Cleveland
Benjamin Harrison
Grover Cleveland
William McKinley
Theodore Roosevelt
William Howard Taft
Woodrow Wilson
Warren G. Harding
Calvin Coolidge
Herbert Hoover
Franklin Roosevelt
Harry S. Truman
Dwight D. Eisenhower
John F. Kennedy
Lyndon B. Johnson
Richard M. Nixon
Gerald Ford
Jimmy Carter
Ronald Reagan
George Bush
Bill Clinton
George W. Bush
Barack Obama

List of Presidents in Aphabetical Order
Abraham Lincoln
Andrew Jackson
Andrew Johnson
Barack Obama
Benjamin Harrison
Bill Clinton
Calvin Coolidge
Chester A. Arthur
Dwight D. Eisenhower
Franklin Pierce
Franklin Roosevelt
George Bush
George W. Bush
George Washington
Gerald Ford
Grover Cleveland
Grover Cleveland
Harry S. Truman
Herbert Hoover
James A. Garfield
James Buchanan
James K. Polk
James Madison
James Monroe
Jimmy Carter
John Adams
John F. Kennedy
John Quincy Adams
John Tyler
Lyndon B. Johnson
Martin Van Buren 
Millard Fillmore
Richard M. Nixon
Ronald Reagan
Rutherford B. Hayes
Theodore Roosevelt
Thomas Jefferson
Ulysses S. Grant
Warren G. Harding
William Henry Harrison
William Howard Taft
William McKinley
Woodrow Wilson
Zachary Taylor
Written with StackEdit.

Tuesday 8 November 2016

Countdown Latch

Countdown Latch

Countdown Latch is one of the other synchronizing mechanism that’s made available in Java. Although it may appear to be very similar to Cyclic Barrier.
Countdown Latch works very similar to a multi-lever latch lock. Access through the lock is possible only when all the levers are exercised (count down)
Java Countdown latch also works on the same principle, one or more threads can be made to wait on the latch using the await() method. This latch is made open only when all the count downs are performed on the latch. The number of count downs requires to open the latch is specified during the initialization of the Countdown Latch.
Few notable differences with Cyclic Barrier.
  • A single thread can perform all the count downs if required as it performs various operations.
  • In case of Cyclic barrier, distinct threads have to arrive and wait at the barrier for it be crossed.
  • Threads performing the countdown do not wait at the latch after the count down.
Create a CountDownLatch with the number of countdowns
CountDownLatch latch = new CountDownLatch(2);
We, will create a simple program that would perform addition of two matrices (2*2). To achieve parallelism, each row of the matrix is worked on by a seperate thread.
class Matrix {
    CountDownLatch latch;
    ExecutorService executorService;
    int[][] result;
    Matrix() {
        this.latch = new CountDownLatch(2);
        executorService = Executors.newFixedThreadPool(2);
    }
}
Here,
latch has been initialized with value two
executor service created with fixed Thread Pool for two threads
int[][] add(int[][] matrix_a, int[][] matrix_b) {
        int[][] result = new int[matrix_a.length][matrix_a[0].length];

        class AddWorker implements Runnable {
            int row_number;

            AddWorker(int row_number) {
                this.row_number = row_number;
            }

            @Override
            public void run() {
                for (int i = 0; i < matrix_a[row_number].length; i++) {
                    result[row_number][i] = matrix_a[row_number][i]
                            + matrix_b[row_number][i];
                }
                latch.countDown();
            }
        }

        executorService.submit(new AddWorker(0));
        executorService.submit(new AddWorker(1));

        try {
            System.out.println("Waiting for Matrix Addition");
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        return result;
    }
}
The add() method creates two AddWorker instances. Each instance works on performing addition on one row of the matrix determined by the row_number passed in the constructor.
The add() method calls latch.await() which will cause it to block as it is the only thread currently waiting at the latch.
The latch is open when the two worker threads does a countdown on the latch. Two countdowns are required on the latch.
public class CountDownLatchDemo {

    public static void main(String[] args) {
        int[][] matrix_a = { { 1, 1 }, { 1, 1 } };
        int[][] matrix_b = { { 2, 2 }, { 3, 2 } };

        MatrixCountDown _matrix = new MatrixCountDown();
        int[][] result = _matrix.add(matrix_a, matrix_b);
        printMatrix(result);

    }

    public static void printMatrix(int[][] x) {
        for (int[] res : x) {
            for (int val : res) {
                System.out.print(val + ", ");
            }
            System.out.println(" ");
        }
    }

}
The key difference from a similar application written using cyclic barrier would be
  • Worker threads are not waiting after calling the countdown operations. Only threads that make call to await() operation on the latch wait
  • latch is the initialized to the number of countdown operations and not on the number of threads required to wait on it. In case of Cyclic barrier, barrier is initialized with the number of threads that needs to wait at the barrier.
Output from the Demo application
Waiting for Matrix Addition
3, 3,  
4, 3,  

Cyclic Barrier

Cyclic Barrier

Cyclic Barrier is one of the synchronizing mechanism made available in Java. Lets imagine it like a barrier in the actual sense which require a fixed number of parties to arrive to cross it.
Below line creates a barrier that requires three threads to cross it.
CyclicBarrier barrier = new CyclicBarrier(3);
We, will create a simple program that would perform addition of two matrices (2*2). To achieve parallelism, each row of the matrix is worked on by a seperate thread.
class Matrix {
    CyclicBarrier barrier;
    ExecutorService executorService;
    int[][] result;
    Matrix() {
        this.barrier = new CyclicBarrier(3);
        executorService = Executors.newFixedThreadPool(2);
    }
}
Here,
- barrier waiting on three threads to arrive.
- ExecutorService using a fixedThreadPool to schedule the threads
- int [][]result stores the exectuion result of a matrix operation.
int[][] add(int[][] matrix_a, int[][] matrix_b) {
        class AddWorker implements Worker {
            int row_number;
            AddWorker(int row_number) {
                this.row_number = row_number;
            }
            @Override
            public void run() {
                for (int i = 0; i < matrix_a[row_number].length; i++) {
                    result[row_number][i] = matrix_a[row_number][i] + matrix_b[row_number][i];
                }
                try {
                    System.out.println("Completed for Row  " + row_number);
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }
        result = new int[matrix_a.length][matrix_a[0].length];
        executorService.submit(new AddWorker(0));
        executorService.submit(new AddWorker(1));
        try {
            System.out.println("Waiting for Matrix Addition");
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        return result;
    }
The add() method creates two AddWorker instances. Each instance works on performing addition on one row of the matrix determined by the row_number passed in the constructor.
The add() method calls barrier.await() which will cause it to block as it is the only thread currently waiting at the barrier.
The barrier is overcome only when both the AddWorker instances also call barrier.await().
public class CyclicBarrierDemo {
    public static void main(String[] args) {

        int[][] matrix_a = { { 1, 1 }, { 1, 1 } };
        int[][] matrix_b = { { 2, 2 }, { 3, 2 } };

        Matrix _matrix = new Matrix();
        int[][] result = _matrix.add(matrix_a, matrix_b);
        printMatrix(result);

        int[][] matrix_c = { { 10, 10 }, { 12, 11 } };
        int[][] matrix_d = { { 22, 22 }, { 13, 12 } };

        result = _matrix.add(matrix_c, matrix_d);
        printMatrix(result);
    }

    public static void printMatrix(int[][] x) {
        for (int[] res : x) {
            for (int val : res) {
                System.out.print(val + ", ");
            }
            System.out.println(" ");
        }
    }
}
Demo Application performs addition of two matrices using the add() method.
Since barriers can be reused. We can call the add() method mutliple times without having to reset the synchronizer.

Output of the Matrix Operation.


Waiting for Matrix Addition
Completed for Row  0
Completed for Row  1
3, 3,  
4, 3,  
Waiting for Matrix Addition
Completed for Row  0
Completed for Row  1
32, 32,  
25, 23,