Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Friday, 17 June 2016

Iterator Design Pattern

Background

In one of the previous posts we saw Introduction to Design Patterns. In that we learned how different design patterns solve some pre identified design concerns and provide a good solution. Above post also states types of design patterns and links to design patterns we have already covered. In this post we will see another design patter - Iterator pattern. Is it same as the iterator I use to iterate over collections? Yes it is! And that a design pattern? What problem does that solve? Hold on to that we will come there in some time :)



Problem

Lets say there are two companies - Company A and company B. They both maintain employee records for their respective employees and their implementation is something like below - 

Company A Employee records - 

/**
 * 
 * @author athakur
 *
 */
public class CompanyAEmpRecords {

    private Employee[] companyEmployees = new Employee[10];
    private int index = -1;

    public void addEmployee(Employee newEmployee) {
        if (index == 10) {
            throw new RuntimeException("Maximum employee limit reached");
        }
        companyEmployees[index++] = newEmployee;
    }

    public void removeEmployee(String name) {
        // implementation to remove employee
    }

    public int getNoOfEmployees() {
        return index + 1;
    }
    
    public Employee[] getEmployees() {
        return companyEmployees;
    }

}

Company B Employee records - 

/**
 * 
 * @author athakur
 *
 */
public class CompanyBEmpRecords {
    private List<Employee> companyEmployees = new ArrayList<>();

    public void addEmployee(Employee newEmployee) {
        companyEmployees.add(newEmployee);
    }

    public void removeEmployee(String name) {
        // implementation to remove an employee based on name
    }

    public int getNoOfEmployees() {
        return companyEmployees.size();
    }
    
    public List<Employee> getEmployees() {
        return companyEmployees;
    }

}

Life was all good when they were working independently. Company A was small and sufficient with less than 10 employees where as Company B did not really care how many employees joined. But then one day they decided to merge and expand their business. Employees of both the companies will now be under one entity and the task to create code that lists down both company's employees now rests on you. You know both Employee record implementation of companies. So you start writing code using it.


/**
 * 
 * @author athakur
 *
 */
public class CompanyRecordsPrinter {
    
    public void pringCompanyEMployeeRecords(CompanyAEmpRecords companyAEmpRecords, CompanyBEmpRecords companyBEmpRecords) {
        
        Employee[] companyAEmployees = companyAEmpRecords.getEmployees();
        for(int i=0; i< companyAEmpRecords.getNoOfEmployees();i++) {
            System.out.println(companyAEmployees[i]);
        }
        
        List<Employee> companyBEmployees= companyBEmpRecords.getEmployees();
        for(Employee emp : companyBEmployees) {
            System.out.println(emp);
        }
        
    }

}

Well that serves the purpose. We are printing employees in both companies using their records. But is it a good design. Two loops for two different types of data structures. What if Company C is merged with this later. Add a new loop to handle it? Naah. Something does not feel right. This is where iterator pattern comes into picture.

Iterator Pattern defined

The Iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing it's underlying representation.

Solution

You will basically have a common interface called Iterator which will have methods like -
  • boolean hasNext()
  • Object next()
Each Employee Record class will have a method called getIterator() that will basically return corresponding new instance of Iterator. Lets call it -
  • CompanyAEmpRecordsIterator
  • CompanyBEmpRecordsIterator
Then you can have a common method that take an Object of type Iterator and iterate over it using hasNext() method and get the actual data using next() method.

Sample code -

public class CompanyAEmpRecords implements CompanyEmpRecords {

    private Employee[] companyEmployees = new Employee[10];
    private int index = -1;

    @Override
    public void addEmployee(Employee newEmployee) {
        if (index == 9) {
            throw new RuntimeException("Employees limit reached");
        }
        companyEmployees[++index] = newEmployee;
    }

    @Override
    public void removeEmployee(Employee oldEmployee) {
        int i = 0;
        for (; i <= index; i++) {
            if (companyEmployees[i].equals(oldEmployee)) {
                break;
            }
        }
        for (int j = i; j <= index - 1; j++) {
            companyEmployees[j] = companyEmployees[j + 1];
        }
        companyEmployees[index] = null;
        index--;

    }

    @Override
    public int getNoOfEmployees() {
        return index + 1;
    }

    @Override
    public Iterator getIterator() {
        return new CompanyAEmpRecordsIterator();
    }

    private class CompanyAEmpRecordsIterator implements Iterator {

        int currIndex = -1;

        @Override
        public boolean hasNext() {
            if (currIndex + 1 <= index)
                return true;
            else
                return false;
        }

        @Override
        public Object next() {
            if (currIndex + 1 <= index)
                return companyEmployees[++currIndex];
            else
                return null;
        }

    }

}


You get the point.  And your printing logic will be as simple as  -

    public void pringCompanyEMployeeRecords(CompanyAEmpRecords companyAEmpRecords, CompanyBEmpRecords companyBEmpRecords) {
        
        printRecord(companyAEmpRecords.getIterator());
        printRecord(companyBEmpRecords.getIterator());
    }
    
    private void printRecord(Iterator recordIterator) {
        while(recordIterator.hasNext()) {
            System.out.println(recordIterator.next());
        }
    }


This is just the snippet I have provided. You can download the complete code from my git repository -
NOTE : Instead of defining your own iterator interface you can use java.util.Iterator interface instead.

NOTE :  we have not added remove() method in the Iterator interface. Neither are we handling multi threading scenarios like what happens when the collection gets modified when you are iterating using that iterator. The way this is handled is that when iterator is created we copy the modcount (modification count) and at any point during the iteration this is different than the original count we throw java.util.ConcurrentModificationException.

For sample code you can refer to Iterator provided by ArrayList class in Java -

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }


Modification count and ConcurrentModificationException


Lets try to understand modcount we just discussed above in a better way. Now a collection when initialized has a variable called

protected transient int modCount = 0;

This keeps track of modifications made to the collection. Now when you create an iterator for your collection this modcount gets copied over to your iterator as expectedModCount -

int expectedModCount = modCount;

Now during each iterator of iterator checkForComodification() method is called which does following -

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

So if modCount of the collection is not same as what was copied over to it's iterator during it's creation (stored as expectedModCount) then it throws ConcurrentModificationException.

Exception for this is when you use iterators remove method in which case iterator updates it's expectedModCount accordingly.

Class Diagram



Related Links

Monday, 16 February 2015

Proxy Design Pattern in Java

Background

We know proxy design pattern involves a representative object that controls access to it's subject that may be - 
  1. Remote
  2. Expensive to create (Virtual Proxy) or
  3. Need secure access (Protection Proxy)
In last post on

Understanding Java Remote Method Invocation (RMI)

We say example of Remote proxy. Stub is essentially the proxy that controls access of actual remote object.

Here is the summary of what happens in Proxy design pattern -

Proxy class implements the same interface as that of the Subject. Client crates a instance of proxy class (Typically using Factory pattern.) rather than the actual subject and calls methods on proxy (this is possible since both proxy and subject implement same interface). Now proxy internally instantiates Subject and calls methods on it depending on the purpose of the proxy.




We will see example of both Virtual as well as Protection proxy in this example. Later we will also see how proxies are dynamically created (Java has in built support for it).

 Virtual Proxy

Lets say we are creating a news website. Lets design Interface for it - 

public interface NewsSiteInterface {
    void showNews();
}

Now lets write the actual implementation - 
public class NewsSiteImpl implements NewsSiteInterface {
    
    String news;
    
    public NewsSiteImpl() {
        //simulate blocking data transfer
        try {
            Thread.sleep(5000);
            System.out.println("Data Received");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        news = "Hello World";
    }
    
    public void showNews() {
        System.out.println(news);
    }

  
}


Notice the constructor simulates fetching data which is a block call. If you directly make instance of NewsSiteImpl and call showNews() on it site may possible hang as instance creation will take time. Lets now create a proxy that would avoid this blocking call.


public class NewsSiteProxy implements NewsSiteInterface {
    
    NewsSiteInterface newsSite;
    
    public NewsSiteProxy() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                newsSite = new NewsSiteImpl();
                showNews();
            }
        }).start();
    }

    @Override
    public void showNews() {
        if(newsSite == null) {
            System.out.println("Loading....");]
        }
        else {
            newsSite.showNews();
        }
        
    }

}

So now we create instance of  NewsSiteInterface in another thread asynchronously. So user can go ahead and call showNews(). Obviously data may not be loaded by then, So we just show Loading...
Important point out program will not get hanged. Lets test out setup.

public class NewsDemo {
    public static void main(String args[])
    {
        NewsSiteInterface newSite  = new NewsSiteProxy();
        newSite.showNews();
        newSite.showNews();
    }
    
}

and the output is -

Loading....
Loading....
Data Received
Hello World

So that was our virtual proxy that helped us tackle creating on expensive time consuming instance.

Now lets see our protection proxy. Well the concept remains the same. Instead of doing task asynchronously we do some validation.

 In our next protection proxy demo we will use Java Dynamic proxies.

Protection Proxy and Java Dynamic proxy

Lets say we are designing a programming QnA site like Stack Overflow.  When user create a account on Stack Overflow he essentially created a profile. Lets write a class for that -


public interface StackOverflowProfile {
    String askQuestion(String question);
    String writeAnswer(String answer);
    void upVote();
    void downVote();
}


Now lets create a concrete implementation of this profile interface.

public class StackOverflowProfileImpl implements StackOverflowProfile {

    @Override
    public void askQuestion(String question) {
        //Ask Question
    }

    @Override
    public void writeAnswer(String answer) {
        //Provide Answer to a question
    }

    @Override
    public void upVote() {
        //Up vote an Answer or Question
        
    }

    @Override
    public void downVote() {
        //Down vote an Answer or Question
    }

}


So far so good. Program would work but we did a major mistake here. We do not have verification check in the code which means a user can keep asking questions, answer them and keep upvoting the same thereby increasing his or her reputation.  Only if we knew proxy pattern before :)

Lets divide out auth checks / Proxy into two parts -
  1. Owner of a Question
  2. Non Owner
Our use case is -
  • Owner can ask question, answer question but cannot do upvote or downvote.
  • Non owner cannot ask question but he can answer, upvote or downvote.
Note : Each profile can use either of the proxy depending on if he or she is the owner of the Question. If owner then Owner Proxy will be used and upvote or downvote operations will not be allowed. If non owner proxy is used then question cannot be asked (as someone else is the owner) but answer, upvote, dowvote operations are allowed.

We are now going to use Dynamic proxies to implement above checks -

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class OwnerSOProfile implements InvocationHandler {
    
    StackOverflowProfile soProfile;
    
    public OwnerSOProfile(StackOverflowProfile soProfile)
    {
        this.soProfile = soProfile;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        try
        {
            if(method.getName().equalsIgnoreCase("askQuestion"))
            {
                method.invoke(proxy, args);
            }
            else if(method.getName().equalsIgnoreCase("writeAnswer"))
            {
                method.invoke(proxy, args);
            }
            else if(method.getName().equalsIgnoreCase("upVote"))
            {
                throw new IllegalAccessException("Cannot Up vote own question or answer");
            }
            else if(method.getName().equalsIgnoreCase("downVote"))
            {
                throw new IllegalAccessException("Cannot down vote own question or answer");
            }
        }
        catch(InvocationTargetException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}




and

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class NonOwnerSoProfile implements InvocationHandler {
    
    StackOverflowProfile soProfile;
    
    public NonOwnerSoProfile(StackOverflowProfile soProfile)
    {
        this.soProfile = soProfile;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        
        try
        {
            if(method.getName().equalsIgnoreCase("askQuestion"))
            {
                throw new IllegalAccessException("Cannot edit question as you are not the owner");
            }
            else if(method.getName().equalsIgnoreCase("writeAnswer"))
            {
                method.invoke(proxy, args);
            }
            else if(method.getName().equalsIgnoreCase("upVote"))
            {
                method.invoke(proxy, args);
            }
            else if(method.getName().equalsIgnoreCase("downVote"))
            {
                method.invoke(proxy, args);
            }
        }
        catch(InvocationTargetException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}



and finally lets do a demo -

import java.lang.reflect.Proxy;

public class SODemo {
    
    public static void main(String args[])
    {
        //general profile
        StackOverflowProfile profile = new StackOverflowProfileImpl();
        //allowed
        (profile).askQuestion("What is proxy pattern?");
        //not allowed
        getOwnerSoProxy(profile).upVote();
        //not allowed
        getNonOwnerSoProxy(profile).askQuestion("Java anti patterns?");
        //alowed
        getNonOwnerSoProxy(profile).upVote();
    }
    
    public static StackOverflowProfile getOwnerSoProxy(StackOverflowProfile profile)
    {
        return (StackOverflowProfile) Proxy.newProxyInstance(profile.getClass().getClassLoader(), profile.getClass().getInterfaces(), new OwnerSOProfile(profile));
    }
    
    public static StackOverflowProfile getNonOwnerSoProxy(StackOverflowProfile profile)
    {
        return (StackOverflowProfile) Proxy.newProxyInstance(profile.getClass().getClassLoader(), profile.getClass().getInterfaces(), new NonOwnerSoProfile(profile));
    }

}

Note : For above demo code. Try one call at a time because we have not added any Exception handling so whenever IllegalAccess Exception is thrown JVM will terminate.

Related Links

Monday, 9 February 2015

Adapter and Facade Design Patterns in Java

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 -

import java.util.Iterator;


public class CostComputer {
    
    public static int computeCost(Iterator<Product> iterator)
    {
        int cost = 0;
        while(iterator.hasNext())
        {
            cost = cost + iterator.next().getCost();
        }
        return cost;
    }
    
}


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 -

public class Toy implements Product {

    int cost;
    
    public Toy(int cost)
    {
        this.cost = cost;
    }
    
    @Override
    public int getCost() {
        return cost;
    }

}


and

import java.util.Enumeration;
import java.util.Random;
import java.util.Vector;


public class ToysCreator {
    
    int count;
    
    public ToysCreator(int count)
    {
        this.count = count;
    }
    
    public Enumeration createToys()
    {
        Vector toys = new Vector<>();
        for(int i=0; i<count ;i++)
        {
            toys.add(new Toy(new Random().nextInt(10)));
        }
        return toys.elements();
    }

}


and then they tried to use your code as follows -

public class ToysCostComputer {
    
    public static void main(String args[])
    {
        System.out.println(CostComputer.computeCost(new ToysCreator(6).createToys())); // this will fail
    }

}


and viola -

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.

It goes as follows -

import java.util.Enumeration;
import java.util.Iterator;


public class EnumToIteratorAdapter implements Iterator<Product> {

    Enumeration<Product> enumeration;
    
    public EnumToIteratorAdapter(Enumeration<Product> enumeration)
    {
        this.enumeration = enumeration;
    }
    
    @Override
    public boolean hasNext() {
        return enumeration.hasMoreElements();
    }

    @Override
    public Product next() {
        return enumeration.nextElement();
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
        
    }

}


and now client can use our code with the help of Adapter

import java.util.Iterator;


public class ToysCostComputer {
    
    public static void main(String args[])
    {
        Iterator toysIterator = new EnumToIteratorAdapter(new ToysCreator(6).createToys());
        System.out.println(CostComputer.computeCost(toysIterator));
    }

}


and the output is - 27. Some random number but you get the point.

Class Diagram for our above demo is as follows -



Generic Class diagram for Adapter Pattern is as follows -



That was Adapter Pattern. Now lets come to facade pattern.

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 -


Lets say you have multiple modules for handling program bugs. May be
  1. class BugCreator that creates various types of bugs - UI, functional, localization etc. 
    • Methods : createBug(String bugType) etc
  2. class BugsReplicator that tries replicates the bug as per the description of filed bug.
    • Methods :  replicateBug(Bug newBug) etc
  3. class BugsSolver that finds the fix and checks in the code.
    • Methods : fixBug(Bug newBug) etc
  4. class BugsDeployer that deploys the fix to dev or qa environments.
    • Methods : deployFix(CodeFix fix) etc
  5. 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.

public boolean resolveBug(String desc, String bugType)
{
      Bug newBug =  new BugCreator().createBug(bugType);
      boolean replicated = new BugsReplicator .replicateBug(newBug);
      if(replicated)
      {
          CodeFix fix = new BugsSolver().fixBug(newBug);
          new BugsDeployer().deployFix(fix);
          if(new BugsTester.testFix(Bug bug))
          {
              return true;
          }
          else
          {
              return false;
          }
      }
      else
      {
          return false;
      }
}


Now this is just an example that I am giving to help you understand how Facade pattern simplifies subsystem complexity. 


Notes

  • Facade does not encapsulate subsystem classes. It simply provides simplified interface to complex subsystem classes. Subsystem classes are still accessible for direct use.

Summary

  • Decorator pattern does not alter any interface. It simply adds responsibility.
  • Adapter pattern Converts one interface (Adaptee) to another (Target) for compatibility.
  • Facade pattern simplifies interface for complex subsystem subclasses.

Related Links

Wednesday, 4 February 2015

The Decorator pattern design pattern

Background

This pattern employes a very important OO design principle -
  • Classes should be open for extension but closed for modification.
This design pattern allows new functionality to be added to an existing Object without modifying it's structure.  Also this is the 1st structural design pattern that we are taking a look at. If you remember there are 3 types of design patterns -

  1. Creational
  2. Structural
  3. Behavioral

Lets take an example to understand this better. Lets say you have opened a Pizza shop and you offer various types of Pizzas.



You then created classes for each type of Pizza. Now that you are very well versed with following design principle -
  • Code for interface and not implementation
you would probably create an interface Pizza and then make concrete class like PaneerPizza, ChickenPizza by implementing Pizza interface. But now lets say your business grows and you offer various types of toppings like extra cheese or mushrooms or spicy chicken or corn. For this you will have to now either create new concrete Pizzas or alter existing code. But this is not practical as every time you decide to offer or remove a new topping you code will change (Think of each Pizza having a getCost() method which will differ with toppings). This is where Decorator pattern comes to the rescue.


Generic Class Diagram



Source : Wiki


To the Code....

Lets first create an interface - Pizza

public interface Pizza {
    int getCost();
}

Now lets create concrete classes for Pizza - 

public class PaneerPizza implements Pizza {

    @Override
    public int getCost() {
        return 3;
    }

}

and

public class ChickenPizza implements Pizza {

    @Override
    public int getCost() {
        return 5;
    }

}

And now lets create decorator class. Remember decorator class will implement Component and will also have an instance of Component in it. Also the operation method which is this case is getCost() will be abstract.

public abstract class PizzaDecorator implements Pizza {

    

    Pizza pizza;



    public abstract int getCost();



}

and now lets create concrete classes for Toppings which will extend PizzaDecorato.

public class MushroomToppings extends PizzaDecorator {

    public MushroomToppings(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public int getCost() {
        return 2 + pizza.getCost();
    }

}

and

public class CornTopping extends PizzaDecorator {

    public CornTopping(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public int getCost() {
        return 1 + pizza.getCost();
    }

}

and  that's all with the model classes. Now lets simulate it and see,

/**
 * @author athakur
 */
public class PizzaSimulation {
    
    public static void main(String args[])
    {
        Pizza pizza = new ChickenPizza();
        System.out.println("Pizza cost : " + pizza.getCost());
        
        Pizza pizzaWithCornToppings = new CornTopping(pizza);
        System.out.println("Pizza cost : " + pizzaWithCornToppings.getCost());
        
        Pizza pizzaWithCornAndMushroomToppings = new MushroomToppings(pizzaWithCornToppings);
        System.out.println("Pizza cost : " + pizzaWithCornAndMushroomToppings.getCost());
        
    }
}



And the output is -

Pizza cost : 5
Pizza cost : 6
Pizza cost : 8


Now go back to each Pizza and Topping class and verify the output. It's pretty straight forward. See how we could dynamically add toppings and compute total cost without actually modifying the original class? That the power of Adapter patter.


NOTE : In decorator pattern decorator implements the component and also composes the component.
NOTE : In adapter pattern adapter implements the target and composes the adaptee.

Class Diagram for Above Pizza Store Code

Related Links


Summary

  • Decorator pattern does not alter any interface. It simply adds responsibility.
  • Adapter pattern Converts one interface (Adaptee) to another (Target) for compatibility.
  • Facade pattern simplifies interface for complex subsystem subclasses.

Sunday, 1 February 2015

The Observer Design Pattern

Background

Ever subscribed to a blog, news or a RSS feed? If not you should definitely try it out. It saves time of scanning through the whole content to find posts of your interest especially in this information technology times when there is so much data flowing on the internet. Anyway lets see how this works as it would be crucial in understanding the design pattern that we are going to discuss today -  The Observer Design Pattern.


How Observer Pattern Works?

Lets say we have a new website - www.worldNews.com that provides information of events going on in the entire glob. You on the other hand are Cricket fan and really would like to get all updates of cricket matches all over the globe.



One crude way would be go to the sites sports section and check out cricket events like twice a day or more? But if the site provides an RSS feed for cricket news you can simply subscribe to it and whenever news site publishes something about cricket you will directly get the news feed.   




In The Observer Design Pattern world 'Cricket' is the subject and you are the observer. As an observer you register yourself to the Subject and whenever Subject's state gets updated all the registered observers (including you) get notified. You can also de-register yourself from the update.


Lets write a code in Java for above to get a better understanding of Observer pattern. For the record Java provides an in built support for Observer pattern but we will look at it in some time. For now lets do it from very basics.

Definition

Definition for Observer Design pattern as per Wiki is -

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

Generic Class Diagram



"Observer" by WikiSolved - Own work. Licensed under Public Domain via Wikimedia Commons.

To the code.....

Lets first create our interfaces and model classes - 

Lets first create Subject interface. Later we will create Cricket subject that implements Subject interface. We write interface so that tomorrow we can add  more subjects like finance, political new etc. For this demo we will just see cricket event.

public interface Subject {
    public void registerObserver(Observer observer);
    public void deregisterObserver(Observer observer);
    public void notifyObservers(Event event);
    public void onNewEvent(Event event);
}

Notice how Subject interface has following three methods - 

  1. registerObserver - Each observer will call this method on the Subject he is interested in and will get registered.
  2. deregisterObserver - Observer may choose to de register from getting updates on a subject. I such cases Observer will call this method.
  3. notifyObservers - Whenever subjects state will change this method will be invoked which will push the updated data to the observers who have registered to that subject.
  4. onNewEvent - This method is called whenever new Event is generated. When this happens all we have to do is call notifyObservers.
 Now lets create our Observer interface -

public interface Observer {
    
    public void update(Event event);

}


Notice observer interface has just one method -
  1. update - This method will be invoked on every registered observer by the corresponding subject

Finally lets create an Event interface  . This is just a interface with no methods in it. Each actual event like CricketEvent in our example will implement this interface. Other Events could be FinanceEvent, PoliticsEvent etc

public interface Event {

}

Very important point to note here - Why are we creating interfaces and not direct concrete implementation?

Remember the OO design principles mentioned in Introduction to Design Patterns 

  • Code for interface not implementation
And the reason is quite simple. If you code for concrete implementation then you have to change base code every time new entity is added.


Lets move on to our concrete classes implementations now.

First Lets write our CricketEvent -

public class CricketEvent implements Event {
    

    String team1;
    String team2;
    String matchLocation;
    String matchDate;

    

    public CricketEvent(String team1, String team2, String matchLocation, String matchDate) {
        this.team1 = team1;
        this.team2 = team2;
        this.matchLocation = matchLocation;
        this.matchDate = matchDate;
    }


    @Override
    public String toString() {
        return "CricketEvent [team1=" + team1 + ", team2=" + team2
                + ", matchLocation=" + matchLocation + ", matchDate="
                + matchDate + "]";
    }
    

}


Simple Cricket Event class with some attribute.

Next lets implement our Subject - CricketSubject.

public class CricketSubject implements Subject {

    

    List<Observer> registeredObservers;

    

    public CricketSubject() {
        registeredObservers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer observer) {
        registeredObservers.add(observer);
        
    }

    @Override
    public void deregisterObserver(Observer observer) {
        registeredObservers.remove(observer);
        
    }

    @Override
    public void notifyObservers(Event event) {
        for(Observer observer : registeredObservers) {
            observer.update(event);
        }
    }

   

    @Override
    public void onNewEvent(Event CricketEvent) {
        notifyObservers(CricketEvent);
    }

}


We are using a simple ArrayList to keep track of registered Observers. Whenever new Cricket is generated onNewCricketEvent method is called (you don't have to worry about this. All you have to know is whenever cricket event is generated this will be called.) then we call notifyObservers to notify all observers.

Lets now create class for CricketEventObserver -

public class CricketEventObserver implements Observer {
    
    public CricketEventObserver(Subject subject) {
        subject.registerObserver(this);
    }

    @Override
    public void update(Event event) {
        CricketEvent crickEvent = (CricketEvent) event;
        System.out.println("Received Cricket Event : " + crickEvent);
    }

}


Notice in constructor it takes an Observer reference and registers itself to it. Now lets simulate and see the working -

public class ObserverSimulation {

    public static void main(String args[]) {
       
        Subject cricketSubject = new CricketSubject();
        Observer cricketEventObserver1 = new CricketEventObserver(cricketSubject);
        Observer cricketEventObserver2 = new CricketEventObserver(cricketSubject);
       
        System.out.println("Generating Cricket Event");
        cricketSubject.onNewEvent(new CricketEvent("India", "Aus", "Melbourne Cricket Ground", "01/02/2015"));
        System.out.println("--------------------------");
        System.out.println("De registerting cricket observer 2");
        cricketSubject.deregisterObserver(cricketEventObserver2);
        System.out.println("--------------------------");
        System.out.println("Generating Cricket Event");
        cricketSubject.onNewEvent(new CricketEvent("India", "England", "Eden Gardens", "03/02/2015"));
        System.out.println("--------------------------");
    }
    
}



and the output is -

Generating Cricket Event
Received Cricket Event : CricketEvent [team1=India, team2=Aus, matchLocation=Melbourne Cricket Ground, matchDate=01/02/2015]
Received Cricket Event : CricketEvent [team1=India, team2=Aus, matchLocation=Melbourne Cricket Ground, matchDate=01/02/2015]
--------------------------
De registerting cricket observer 2
--------------------------
Generating Cricket Event
Received Cricket Event : CricketEvent [team1=India, team2=England, matchLocation=Eden Gardens, matchDate=03/02/2015]
--------------------------


as expected.

Class diagram for above Design is -




Java built in support for Observer pattern

Java provided built in support for Observer pattern with following two entities -
  1. class java.util.Observable
  2. interface java.util.Observer

Observable is a class and have methods like addObserver(), deleteObserver() etc where as Observer is an interface with method update() which Observable instance calls while notifying.

Note :
  • Before calling notifyObservers() you need to call setChanged() to mark the state changed. if you miss this notifyObservers() method will just return without notifying the observers.
  •  Also all methods in Observable class are synchronized which makes it's instances thread safe.

Observer pattern used in JDK

This pattern is used extensively in Swing.
javax.swing.AbstractButton class is the Subject and has concrete implementations like javax.swing.JButton. Observer is java.awt.event.ActionListener interface and you can create instances of it and register to JButton to receive Events update.

For example - 

    public static void main(String args[]) {

        JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Observer 1 : Action Event recived from JButton Subject");
                
            }
        });
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Observer 2 : Action Event recived from JButton Subject");
                
            }
        });
        
    }

Above code registers two concrete implementations of ActionListener interface with Subject JButton and whenever any action is triggered on the button these listeners will be notified.

Related Links



Sunday, 18 January 2015

Factory Method and Abstract Factory Pattern

Background

We know design patterns are broadly categorized into three types - 
  1. Creational
  2. Structural
  3. Behavioral
In this post we will see Factory pattern/Factory method and Abstract Factory design patterns which falls under creational design pattern.
One of the most basic OOP principle is  - "Program to an interface not an implementation". This means you should not directly instantiate your object with new operator in your classes. But then that is how we create new objects in Java. Don't we?  Correct! There is no escape from using new operator to instantiate object but we can surely abstract it out to decouple the object creation code.

That is the very purpose of Factory patterns to abstract out creation of Objects. 

  • All Factory patterns encapsulate Object creation.

Lets understand this with an example. 

Simple Factory pattern


Lets say you are running a sandwich store and want to write an API to deliver sandwiches as asked by the customers. 

public class SandwichStore {
   
    public Sandwich orderSandwich(String type)
    {
        Sandwich sw;
        if(type.equalsIgnoreCase("cheese"))
        {
            sw = new CheeseSandwich();
        }
        else if(type.equalsIgnoreCase("grill"))
        {
            sw = new GrillSandwich();
        }
        else
        {
            sw = new RegularSandwich();
        }
        sw.addToppings();
        sw.makeSlices();
        sw.pack();
        return sw;
    }
   
}

 where CheeseSandwich, GrillSandwich and RegularSandwich are concrete implementations of Sandwich class.

Notice code to add toppings, to slice it and packing remain same for all sandwiches. Only change is creating sandwiches depending on the order. Now if tomorrow you decide to add new types of sandwiches or remove existing ones you need to modify above code which is not correct. This is where the factory pattern comes into picture. Job of creating the sandwich is delegated to this factory. See code below -

public class SandwichFactory {
    
    public Sandwich createSandwich(String type)
    {
        Sandwich sw;
        if(type.equalsIgnoreCase("cheese"))
        {
            sw = new CheeseSanwich();
        }
        else if(type.equalsIgnoreCase("grill"))
        {
            sw = new GrillSandwich();
        }
        else
        {
            sw = new RegularSandwich();
        }
        return sw;
    }

}

and then our store would look like - 

public class SandwichStore {
    
    SandwichFactory sf = new SandwichFactory();
    
    public Sandwich orderSandwich(String type)
    {
        Sandwich sw = sf.createSandwich(type);
        sw.addToppings();
        sw.makeSlices();
        sw.pack();
        return sw;
    }
    
}
 

 Notice how we have successfully moved the sandwich creation dependency to new object (Factory). Also SandwichStore has no need now to know about various types of (sandwiches)Object creations. This is a simple Factory pattern.

Factory Method pattern

  • Factory Method pattern encapsulates object creation by letting subclass decide what object to create.

Above Sandwich store code with Factory Method will look something like - 

public abstract class SandwichStore {
   
    public Sandwich orderSandwich(String type)
    {
        Sandwich sw = createSandwich(type);
        sw.addToppings();
        sw.makeSlices();
        sw.pack();
        return sw;
    }
    
    public abstract Sandwich createSandwich(String type);
   
}

class ChineseSandwich extends SandwichStore
{

    @Override
    public Sandwich createSandwich(String type) {
        Sandwich sw;
        if(type.equalsIgnoreCase("cheese"))
        {
            sw = new ChineseCheeseSanwich();
        }
        else if(type.equalsIgnoreCase("grill"))
        {
            sw = new ChineseGrillSandwich();
        }
        else
        {
            sw = new ChineseRegularSandwich();
        }
        return sw;
    }
    
}

Abstract Factory pattern

  • Abstract Factory pattern provides an interface to create family of related objects.
  • Methods of abstract factory are generally Factory methods.
 Code for this would looke something like -

public  class SandwichStore {
    
    SandwichFactory sf;
   
    public SandwichStore(SandwichFactory sf) {
        this.sf = sf;
    }

    public Sandwich orderSandwich(String type)
    {
        Sandwich sw = sf.createSandwich(type);
        Sause sause = sf.createSause();
        sw.addToppings();
        sw.makeSlices();
        sw.pack();
        sw.addSause(sause);
        return sw;
    }
    
    public static void main(String args[])
    {
        SandwichStore sw = new SandwichStore(new ChinesSandwichFactory());
        sw.orderSandwich("cheese");
    }
}

class ChinesSandwichFactory extends SandwichFactory {

    @Override
    public Sandwich createSandwich(String type) {
        //Return Chines type sandwiches
    }
    
    @Override
    public void createSause() {
        //Return Chines type sause
    }
    
}

class IndianChinesFactory extends SandwichFactory {

    @Override
    public Sandwich createSandwich(String type) {
        //Return Indian type sandwiches
    }
    
    @Override
    public void createSause() {
        //Return Indian type sause
    }
    
} 




Note : The createSandwich() and  createSause() methods are in fact a Factory methods. As stated previously each method of Abstract Factory is a Factory Method.

Generally Abstract Factory class will have many such Factory methods each creating unique object of a family of products. Hence Multiple such methods create families of related products (each product corresponding to each factory method).

Note : Above code creates Family of Sandwiches and Family of sauses which are related (we add sause to the sandwich).






In above diagram each product (product1, product2 ...) corresponds to a factory method in Abstract factory (which is implemented uniquely in Factory1, Factory2...)


Difference between  Factory Method and Abstract Factory

  • Factory Method is a single method (perhaps abstract) that uses inheritance to delegate object creation.
  • Abstract Factory is reference to abstract class whose subclass instances create actual objects. Each concrete implementation of abstract factory creates related products having same super class (interface).
  • AbstractFactory pattern uses composition to delegate responsibility of creating object to another class while Factory design pattern uses inheritance and relies on derived class or sub class to create object.






Related Links

Sunday, 9 November 2014

Strategy Design pattern in Java

Background

In my previous post on Introduction to Design Patterns  we saw there are various types of Design patterns. They are mainly categorized into three types - 
  1. Creational
  2. Structural
  3. Behavioral
 In this post we will lean about Strategy Design pattern. This design pattern comes under behavioral type. This design patterns lets you  
  • define family of algorithms or class behaviors that can change at runtime depending on the context involved. To put it in other words 
  • it lets you choose your strategy from a list of predefined ones depending on what would suit your current runtime context.

Class Diagram




 Above class diagram represents the program that I will be using to demonstrate Strategy pattern. Points to note here -

  1. Both concrete type of Strategies i.e AdditionStrategy and SubtractionStrategy implement the interface Strategy that has a common method performOperation() that each implementing class implement.
  2. Also note the composition relationship between Strategy class and Calculator class. It simply means Calculator class owns Strategy class and that Strategy class cannot exist meaningfully without Calculator class.

To the Code

Lets first write own interface class - 

 Strategy.java

/**
 * 
 * @author athakur
 *
 */
public interface Strategy {
    
    public int performOperation(int a, int b);

}


Now lets write our concrete classes that implement above class -

AdditionStrategy.java


/**
 * 
 * @author athakur
 *
 */
public class AdditionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a+b;
    }

}

SubtractionStrategy.java

/**
 * 
 * @author athakur
 *
 */
public class SubtractionStrategy implements Strategy {

    @Override
    public int performOperation(int a, int b) {
        // TODO Auto-generated method stub
        return a-b;
    }

}

and finally our Calculator class - Calculator.java


/**
 * 
 * @author athakur
 *
 */
public class Calculator {
    
    Strategy strategy;

    public Strategy getStrategy() {
        return strategy;
    }

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public int calculate(int a, int b) {
        return strategy.performOperation(a, b);
    }

}

Now lets test our code. Create a class Test.java

/**

 * 

 * @author athakur

 *

 */

public class Test {

    public static void main(String args[]) {

        Calculator calc = new Calculator();

        calc.setStrategy(new AdditionStrategy());

        System.out.println("Additition : " + calc.calculate(5, 2));

        calc.setStrategy(new SubtractionStrategy());

        System.out.println("Subtraction : " + calc.calculate(5, 2));

    }

}

and the output will be as expected - 

Additition : 7
Subtraction : 3

Understanding the pattern via code

 See how we could change the operation using a particular strategy depending on the requirement. Calculator here is own context. When we needed addition we use the Addition Strategy and when we needed Subtraction we used the Subtraction strategy. Note how the context or the Calculator remains the same but the strategy used changes. We are simply using different strategies depending on the requirement at runtime. This type of design is called Strategy pattern.

To sum up -

In Strategy pattern, objects representing various strategies are created and a context object behavior changes depending on these strategies at runtime.

Related Links

Sunday, 24 March 2013

Singleton Design pattern

Singleton Design patterns is the most simple of all the design patterns in Java. It is also the most frequently asked interview question. So lets go ahead and understand what this design pattern is all about.


Understanding Singleton Design pattern

              Singleton as the name suggests there can be only one instance of the class.There are various cases in which we strictly need only one instance of the class. Like for example we Window manager or Print spoolers or filesystems.  There are only two main points in the definition of Singleton Design pattern - 

  1. There must be only instance allowed for the class.
  2. This single instance of the class must be allowed global point of access.
For better understanding see the following class diagram -

 

Singleton instance creation

         Lets see the code first and then we will try to understand it.


package designPatterns;

public class SingletonPatternDemo {

    private static volatile SingletonPatternDemo singleInstance;

    private SingletonPatternDemo() {
    } // Constructor

    public static SingletonPatternDemo getSingleInstance() {
        if (singleInstance == null) {
            synchronized (SingletonPatternDemo.class) {
                if (singleInstance == null) {
                    singleInstance = new SingletonPatternDemo();
                }
            }

        }
        return singleInstance;
    }
}

     Lets understand the code written above. First of all we have the package and the class declaration. Carefully analyze the next line  private static SingletonPatternDemo singleInstance; we have a reference to the object of class SingletonPatternDemo. Note that it is just the reference and we have not created any associated object yet. Another view point can be that we have not yet used any space on heap for any object. This reference is defined as private and static. It is private which mean we cannot directly access it using class objects For Ex. objectName.singleInstance is not allowed. See Access modifiers for more details. Next it is also defined to be static which means the variable belongs to the class and not individual objects. We will get to static keyword in subsequent tutorials but for now you understand it this way - we can access the variable using SingletonPatternDemo.singleInstance i.e className.instanceVariableName. Next we have defined our constructor to be private which means we cannot create any objects by using the new keyword. Only way to create a object is the getSingleInstance() function which is public and static and returns an object of SingletonPatternDemo class. Again static means we can access it using the class Ex. SingletonPatternDemo.getSingleInstance().

         Inside the getSingleInstance() method we first check whether instance of the class is already created. If it is already created we return the same instance of the class(as we are allowed to have only one instance of the class) but if there is no instance of the class that is already created we create one and return it.What we have inside the getSingleInstance() method is what we call a Double locking mechanism which i will 
explain explicitly.But before that lets understand what synchronized is.

Note : 

Also note that the  singleton instance is defined to be volatile. This keyword is used for consistency of data across threads. You know that each thread has it's cache where the data reference by the thread is cached and when a thread modifies the data it is still in it's local cache and may not be visible to other threads. To avoid this problem variables can be declared volatile. By declaring a variable as volatile we essentially instruct JVM not to cache the variable in threads cache. Instead all the reads and writes must directly happen in the main memory.

Understanding synchronized keyword

          This keyword is used when we are dealing with multi-threading. Note that only member functions can be defined as  synchronized not the member variables or class itself. When we declare a function to be synchronized it means only one thread can access it at a given point of time. Other than synchronized functions we can have synchronized blocks like the one we have used in the above code. It also means the same - only one thread can access the block at a given point of time. We will cover this in depth when we go through what do we mean by a class being thread-safe and related advanced topics but till then given information should suffice.Next lets understand what is the Double locking mechanism we talked about.

Understanding Double locking mechanism

     Lets see the above code again


if (singleInstance == null) {
            synchronized (SingletonPatternDemo.class) {
                if (singleInstance == null) {
                    singleInstance = new SingletonPatternDemo();
                }
            }

This is double locking mechanism. Lets see how this works. Now our aim was to allow only single instance of the class. In multi-threading scenario lets say one thread checks  singleInstance finds it to be null and enters the synchronized block. Lets say now there is s context switch or time quantum of the process is over. Next thread takes over, checks if singleInstance is null which is true so even this thread will enter the first if block. Now if we did not have the second check in the synchronized block both thread would go ahead and create an instance of the class. Final result would be we having two instances of our class which is against our Singleton goal. Hence we do a double check once again in the synchronized block. Now since it is in synchronized block only one thread will execute it at a given time and create a instance. When second thread enters this block it will find singleInstance is not null and will not create a new instance. This method is what we call double locking mechanism.

Early and lazy instantiation in singleton pattern

       What we did in above code example is  lazy instantiation which means we create instance of the class only when it is needed. On the other hand we have Early instantiation which means we create the instance once as soon as the class is loaded and return the same when user need it. Code for  Early instantiation is as follows - 


package designPatterns;

public class SingletonPatternDemo {

    private static SingletonPatternDemo singleInstance  = new
 SingletonPatternDemo() ;

    private SingletonPatternDemo() {
    } // Constructor

    public static SingletonPatternDemo getSingleInstance() {
        return singleInstance;
    }
}

  So we create instance of the class as soon as class is loaded and just return it when getSingleInstance() is called. This demonstrates Early instantiation.




Note : 


You must have notice there is no synchronization involved in early initialization. Since Singleton instance is static variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.


Eclipse Snapshot

 


Note : In Java you must have used Runtime class quite some time. For example to execute processes from Java - Runtime.getRuntime().exec(). This Runtime class is a Singleton class. There is only one instance of this class per JVM.



yes as you must have notice it, they have use Early initialization ( not lazy init).

Is Singleton instance garbage collected?

Simple plain answer is No!

This was an issue prior to Java 1.2 in which if singleton instance did not have a global reference it would be garbage collected. This defeated the very purpose of singleton as next reference created a new instance of it. But this was fixed in Java 1.2.

New garbage collection model forbids any of the classes that it has loaded from being garbage collected unless all the classes are unreferenced (in which case the class loaded is itself eligible for GC). So unless the class loader is garbage collected the singleton class having static reference to singleton instance is never eligible for garbage collection. So you can be sure that the singleton instance will never be GCed.


When Singleton does not remain Singleton?

There are various ways Singleton property can be violated
  1. Use reflection to create new instance
  2. Deserialize and Serialize it again
  3. Clone it if it implements Cloneable interface.
  4. Use different class loaders etc.
Prevention :
  1. Create constructor and throw exception from it
  2. Implement Serializable and return same instance in readResolve() method
  3. throw exception from clone method
But the best way to avoid these is to design singleton object using enum : The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

Related Links


t> UA-39527780-1 back to top