Wednesday, 2 March 2011

Iterator Pattern in Java

Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
It also places the task of traversal on the iterator object, not on the aggregate, which simplifies the aggregate interface and implementation and places the responsibility where it should be.
One Real time example of Iterator Pattern is the usage of Remote Controls in Home. This example I came accross when I was reading my husband's blog and found very intresting. I will share the same example with you.
Any Remote Control we use to start pressing up and down and back keys to iterate through the channels.

public interface Iterator {
public Channel nextChannel(int currentChannel);
public Channel previousChannel(int currentChannel);
}


The Channel iterator is common for all the remote controls.It's like a specification implemented by all the remote control manufacturing companies.


public class ChannelSurfer implements Iterator{
public Channel nextChannel(int currentChannel) {
Channel channel=new Channel(currentChannel+1);
return channel;
}
public Channel previousChannel(int currentChannel) {
Channel channel=new Channel(currentChannel-1);
return channel;
}
}


public class RemoteControl {
private ChannelSurfer surfer;
public RemoteControl() {
surfer=new ChannelSurfer();
}
public Program getProgram(ChannelSurfer surfer) {
return new Program(surfer.nextChannel());
}
}

public class Program {// ... Some specific implementation of Program class.}
}


We all know that every channel is associated with program and it's basically the program and not the channel number which a user wants to see.This applies that we can apply some logic before returning the elements through iterator.Iterator here can also be programmed to return 'the programs' straight away rather than returning the channels.
Common Java Iterator is Iterator itself.Interface Signature has been copied from the javadoc.
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
-> Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
-> Method names have been improved.

public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}


java.util.Collection interface a root interface in Collections hierarchy contains a method iterator() which returns the Iterator interface.
Hence any class implementing Collection interface should provide definition for iterator() method.But please note that there are no Guarantees concerning the order(unless this collection is an instance of some class that provides a guarantee) as List by definition guarantees ordered Collection.
When we try to view List interface which extends Collection interface it has a method iterator() which returns an Iterator over the elements in this list in proper sequence.
Now coming to ArrayList a subclass class implementing List interface - which also extends AbstractList class provides definition for iterator() method.Infact all the underlying logic sits in AbstractList class.
When we try to view code it tries to return a Itr innerClass object.

public Iterator<E> iterator() {
return new Itr();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}

 

Other Patterns



Composite Pattern
Iterators are often used to recursively traverse composite structures.
Factory Method
Polymorphic iterators use factory methods to instantiate the appropriate iterator subclass.

Single Responsibility Principle (SRP)

The Single Responsibility Principle.
  • Each responsibility should be a separate class, because each responsibility is an axis of change.
  • A class should have one, and only one, reason to change.
  • If a change to the business rules causes a class to change, then a change to the database schema, GUI, report format, or any other segment of the system should not force that class to change.
So in brief, principle states: There should never be more than one reason for a class to change. Below is an example of some code breaking this principle.

Case 1 : Violating SRP


 
public class WeatherDisplay
{
private int _Temperature;
private int _WindSpeed;

public WeatherDisplay(int temperature, int windSpeed)
{
_Temperature = temperature;
_WindSpeed = windSpeed;
}

public void DisplayWeather()
{
DisplayTemperature();
DisplayWindSpeed();
}

private void DisplayTemperature()
{
println("The current temperature is: " + _Temperature + " degrees celcius.");
}
private void DisplayWindSpeed()
{
println("The current wind speed is: " + _WindSpeed + " meters per second.");
}
}





As you can see there are 2 distinct responsibilities for the class WeatherDisplay (you could even say there are 3 responsibilities). You could say one is to display the temperature and the other is to display the wind speed. Now because we are talking about 2 responsibilities we can also say that there are at least 2 reasons why we would / could change this class in the future, the temperature should be displayed in Fahrenheit and the wind speed should be displayed in knots.

Case 2 : Following SRP


Below we see how we could solve this and be coding according to the Single Responsibility Principle.
WeatherDisplay

public class WeatherDisplay
{
private DisplayTemperature _DisplayTemperature;
private DisplayWindSpeed _DisplayWindSpeed;

public WeatherDisplay(int temperature, int windSpeed)
{
_DisplayTemperature = new DisplayTemperature(temperature);
_DisplayWindSpeed = new DisplayWindSpeed(windSpeed);
}

public void DisplayWeather()
{
_DisplayTemperature.Display();
_DisplayWindSpeed.Display();
}
}
}

TemperatureDisplay

public class DisplayTemperature
{
private int _Temperature;

public DisplayTemperature(int temperature)
{
_Temperature = temperature;
}

public void Display()
{
println("The current temperature is: " +
_Temperature + " degrees celcius.");
}
}

WindSpeedDisplay
public class DisplayWindSpeed
{
private int _WindSpeed;

public DisplayWindSpeed(int windSpeed)
{
_WindSpeed = windSpeed;
}

public void Display()
{
println("The current wind speed is: " +
_WindSpeed + " meters per second.");
}
}

In this second example you can see that I now re-factored the class WeatherDisplay into three classes. Weather Display still exists but now it is using the class TemperatureDisplay and WindSpeedDisplay to actually display the data.

 

Case 3 : Better implementation


As I said before you could even say that there were 3 responsibilities for the first example and they would be displaying the information, providing temperature text markup and providing wind speed text markup. So in that case we would probably re-factor our example in the following way:

Interface: ITextDisplay

public interface ITextDisplay  {
void Display(TextWriter writer);
}
DisplayTemperature

public class TemperatureDisplay implements ITextDisplay
{
private int _Temperature;

public TemperatureDisplay(int temperature)
{
_Temperature = temperature;
}

public void Display(TextWriter writer)
{
writer.WriteLine("The current temperature is: " + _Temperature + " degrees celcius.");
}
}

DisplayWindSpeed


public class WindSpeedDisplay implements ITextDisplay
{
private int _WindSpeed;

public WindSpeedDisplay(int windSpeed)
{
_WindSpeed = windSpeed;
}

public void Display(TextWriter writer)
{
writer.WriteLine("The current wind speed is: " + _WindSpeed + " meters per second.");
}
}

As you can see now instead of providing the class WeatherDisplay with a fixed number of parameters we can now provide it with an unlimited amount of ITextDisplay implementations. The class WeatherDisplay is now responsible for providing a proper TextWriter and telling each ITextDisplay implementation to display its information. The ITextDisplay implementations now only have to write its information to the provided writer, and thus also implementing the Liskov Substitution Principle.



Template Method Pattern

Template method defines the skeleton of Algorithm(steps of algorithm) in a method, differing some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
The objective is to ensure that algorithm's structure stays unchanged, while subclasses provide some part of implementation.

This pattern is all about creating a template for an algorithm. Here Template is nothing but a method; more specifically it is a method that defines an algorithm as a set of steps.
Let us look at an example :

abstract class Generalization {
// 1. Standardize the skeleton of an algorithm in a
//"template" method
public final void findSolution() {
stepOne();
stepTwo();
stepThr();
hook();
}
// 2. Common implementations of individual steps are defined
//in base class
protected void stepOne() {
System.out.println( "Generalization.stepOne (Common)" );
}
// 3. Steps requiring particular impls are "placeholders"
//in the base class
abstract protected void stepTwo();
abstract protected void stepThr();
// 4. This is hook method (concrete method) which
//provides default implementation, but
//allows subclasses to override if necessary.
protected void hook() {
System.out.println( "This is default
implementation of hook method"
);
}
}
class SpecializationOne extends Generalization {
// 5. Derived classes can override placeholder methods
protected void stepThr() {
System.out.println( "SpecializationOne.stepThr" );
}
protected void stepTwo() {
System.out.println( "SpecializationOne.stepTwo" );
}
}
class SpecializationTwo extends Generalization{
// 5. Derived classes can override placeholder methods
protected void stepTwo() {
System.out.println( "SpecializationTwo .stepTwo" );
}
protected void stepThr() {
System.out.println( "SpecializationTwo.stepThr" );
}
protected void hook() {
System.out.println( "SpecializationTwo.hook" );
}
}


Hook is a method that is declared in abstract class, but only given empty or default implementation. This gives the subclasses the ability to hook into the algorithm at various points, if they wish. Subclass is also free to ignore the hook method.
When to use abstract method and when to use hooks?
Use abstract methods when your subclass must provide the implementation. Choose hook when it is optional for subclasses to implement it.



Hollywood Priciple:



Don't call us we will call you.
Hollywood Priciple allows us to prevent dependency rot.
With the hollywood priciple, we allow low level components to hook themselves into a system. But high level components decide when they are needed and how... In other words high level components give 'don't call us, we will call you' treatment to low level components.
The connection between Hollywood Principle and Template Method Pattern is probably somewhat apparent.
In our above example Generalization is our high-level component. It has control over the sequence of methods to be called and calls on the subclasses only when they are needed for implementation of a method.
Client will depend on Generalization rather than concrete SpecializationOne or SpecializationTwo which reduces dependencies in overall system.
The subclasses never call abstract class directly without being 'called' first.




Difference between Dependency Inversion Principle and Hollywood Principle
Dependency Inversion principle tells us to avoid use of concrete classes and instead work as much as possible with abstractions.
The Hollywood princple is a technique for building frameworks or components so that lower level components can be hooked into computation but without creating dependencies between lower level components and higher level layers.
So they both have goal of decoupling but Dependency Inversion Principle makes a strong and general statement about how to avoid dependencies in design.
The Hollywood principle gives us a technique for creating designs that allow low level structures to interoperate while preventing other classes from becoming too dependent on them.




Advantages of Using The Template Method Design Pattern
1. No code duplication between the classes
2. Inheritance and Not Composition
Whenever a design pattern uses inheritance as a key element instead of composition, you need to consider the reason. To understand the reason, you need to fully understand the principle of favoring composition over inheritance as a general principle in good OOP. The principle's established because of certain advantages of composition over inheritance, especially the composition advantage of not breaking encapsulation. However, Gamma, Helm, Johnson and Vlissides (GoF) note that inheritance also has certain advantages. One such advantage is that when using subclasses where some but not all operations are overridden, modifying the reused implementation is easier. Because the Template Method design pattern does exactly that—uses some but not all operations that can be overridden to achieve flexibility—it incorporates a key advantage of inheritance over composition.
3. By taking advantage of polymorphism the superclass automatically calls the methods of the correct subclasses.


Comparision of different Patterns:
Template Method Pattern : Subclasses decide how to implement steps in an algorithm.
Strategy Pattern : Encapsulates interchangable behaviours and use delegation to decide which behaviour to use.
Factory Method: Subclasses decide which concrete classes to create.

Facade Pattern

Facade provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easy to use.

Facade pattern works on principle of least knowledge.

A Facade not only simplifies an interface, it also decouples a client from subsytem of components. Using Facade Pattern you can take a complex subsystem and make it easier to use by implementing a Facade class that provides resonable interface.

Need for Facade


For Example,Let us think we have subsytem containing Gate, GarageDoors, CarLock, Lights etc.. Now when we leave home we have to following:

door.open();
lights.off();
door.close();
garageDoor.open();
carLock.unlock();
gate.open();
garageDoor.close();
gate.close();


This is a small subsystem, but consider you have bungalow, things get more complicated. Not only this, when the person comes back , he has to do following things:


gate.open();
garageDoor.open();
carLock.lock();
door.open();
lights.on();
gate.close();
garageDoor.close();
door.close();

Again a hell lot of work. Wouldn't be it good, if we have some smart system, which does all this itself, rather than we go and click all these to work. This is where facade pattern comes into picture.

Instead of doing all that stuff and making lots of object in our main class, we supply all these components to our facade class, which deals with these components and solve these problems. Now we will be having a single iterface which will do simplify the subsystem for us:


public class HomeFacade{
Gate gate;
GarageDoor garageDoor;
CarLock carLock;
Lights lights;
MainDoor door;

public HomeFacade(Gate gate,GarageDoor garageDoor,CarLock carLock,Lights lights,MainDoor door){
this.gate = gate;
this.garageDoor = garageDoor;
this.carLock = carLock;
this.lights = lights;
this.door = door;
}

public void reachHome(){
gate.open();
garageDoor.open();
carLock.lock();
door.open();
lights.on();
gate.close();
garageDoor.close();
door.close();
}

public void leaveHome(){
door.open();
lights.off();
door.close();
garageDoor.open();
carLock.unlock();
gate.open();
garageDoor.close();
gate.close();

}
}


The Facade still leaves the subsystem accessible to be used directly. If you need the advanced functionality of the subsystem classes, they are avilable for your use. (As Facade doesn't encapsulate the subsystem classes, but it provides a simplified interface)
Facade is free to add its own specialization in addition to making use of subsystem.
For a subsystem, we can have number of Facades.


Design Principle behind Facade pattern :



Priciple of least knowledge : When you are designing a system, for any object be careful of the number of classes it interacts with and also how it interacts with those classes. Also known as law of Demeter.
This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts. when you build a lot of dependencies between many classes, you are building a fragile system that is costly to maintain and complex for others to understand.
But how to implement this design priciple?
Take any object. Now from any method in that object, we should only invoke methods that belong to
1. The Object itself
2. Objects passed in as a parameter to the methods
3. Any object that method creates and instantiates.
4. Any components of objects. (Has-A relationship)
(Dont call methods on objects that were returned from calling other methods)
Example :



Without principle :


public float applyForJob(){
Agency agency = company.getAgency();
return agency.searchJob();
}


Here we are dependent on Agency Class also



With principle:


public float applyForJob(){
return company.searchJob();
}



This reduces the number of classes we are dependent on.
Primary benifit is that the calling method doesn't need to understand structural makeup of the object it's invoking methods upon.
The obvious disadvantage of using this principle is that we must create many methods that only forward method calls to the containing classes internal components. This can contribute to a large and cumbersome public interface.
An alternative to this principle or variation on its implementation, is to obtain a reference to an object via a method call, with the restriction that any time this is done, the type of reference obtained is always an interface datatype. As we are binding ourselves with directly to the concrete implementation of a complex object, but instead we are depending on abstractions of which the complex object is composed.


A very nice example of the above approach is java.sql.ResultSet interface.
After an SQL statement has been executed, Java stores results in a ResultSet Object. One of our options at this point is to query this resultset object and obtain metainformation pertaining to this set of data. The class that contains this metadata is ResultSetMetaData class and it's contained with resultset class. We cant directly obtain reference of this class, but instead would call methods on the ResultSet which subsequently forward these requests to ResultSetMetaData Class. This would results in explosion of methods on ResultSet class. Therefore getResultSetMetaData() method on ResultSet would does return a reference to ResultSetMetaData. However as ResultSetMetaData is an interface we are not bound to any concrete implementation contained within resultset.


Difference between Adapter pattern and facade Pattern:
Adapter Pattern changes the interface of one or more classes into one interface that a client is expecting while a Facade may provide a simplified interface to a single class with a very complex interface.
Facade and Adapter may wrap multiple classes but facade's intent is to simplify and adapter's intent is to convert the interface to something different.
Hope it will be useful.

Pattern and their intent

Pattern Intent
Decorator Converts one interface to another
Adapter Doesn’t alter the interface, but adds responsibility
Facade

Makes an interface simpler

Composite

Clients treat collections of objects and individual objects uniformly

Iterator

Provides a way to traverse a collection of objects without exposing the collection’s implementation

Decorator vs Adapter pattern

 

The purpose of the adapter pattern (aka wrapper) is to convert (or present) the interface of an existing class, into an interface that is compatible with an otherwise incompatible client class. In an adapter class, you are actually changing the interface that is being presented (not the actual class's public methods, but by wrapping the class in another class). No new functionality is created in an adapter class, it merely does as its name implies, makes two things that weren't designed to fit together - fit together.

A decorator class does not change the interface of the original class, but may extend it with additional functionality. The decorator pattern allows for the functionality of the original class to be modified at runtime without subclassing. A decorator is slightly confusing to explain but: it is a subclass of a component class, that takes a concrete instance of the component class in it's constructor, and will will either proxy method calls to the concrete instance that was passed in, or provide it's own implementation.

  Adapter / Wrapper Decorator
Composes "origin" class True True
Modifies original interface True False
Modifies behavior of interface
False True
Proxies method calls True True
 

The adapter class will proxy calls from the interface to the client to the interface of the original class that is being wrapped. The adapter class may perform translation upon the inputs of the client class that are being passed to the original class, and upon the output from the original class that are being returned to the client class.

Often, the use of an adapter, or wrapper, pattern is to bridge new code with legacy code, especially when the legacy code cannot be modified. For instance, a library, or software package that exists in a system that cannot be updated, but needs to be communicated with is a good candidate to be wrapped.

UML Abstraction of Adapter / Wrapper Pattern

UML Abstraction of Decorator Pattern
UML of decorator pattern

Example

Legacy class Importer writes data to a database. The legacy class Importer has a method called, import() that takes a string in CSV format. Unfortunately, we have a new tool called SlickExporter. It exports data only in JSON. To make these two classes talk to eachother, we provide a wrapper, aka adapter, class around Importer called ImporterWrapper that now accepts JSON, and translates it to the CSV format that the Importer requires.

Adapter pattern / Wrapper pattern

Adapter Pattern converts interface of a class into another interface that client expects. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
This pattern is also known as Wrapper pattern.


Example in Real life


British plugs OR Indian plugs are cylindrical and American plugs are recangularish. You can use an adapter in between to fit an American (rectangular) plug in British (cylindrical) socket assuming voltage requirements are met with.


Types of Adapters
There are two kinds of adapters( base on composition vs inheritance).
1. Object Adapters (based on composition )
2. Class Adapters(based on inheritance)

Adapter pattern using composition


Object Adapters : Object Adapters use a compositional technique to adapt one interface to another. The adapter inherits the target interface that the client expects to see, while it holds an instance of adaptee. Object adapters enable the client and the adaptee to be completely decoupled from eachother. Only the adapter knows about both of them.

Before going deeper let us have a simple example.
Consider the scenario where our legacy code that exposes the Enumerator interface, but we want our new code to only use iterators.

Here EnumerationIterator is our Adapter.
As we know Enumerator does not support remove(). There is no way to implement a fully functioning remove() method on the adapter. So let us try to throw RunTimeException. As we know remove() method in Iterator throws Unsupported Operation Exception. As long as client is careful (watchout for potential exceptions) and the adapter is well documented it is perfectly reasonable solution.
/*
* We are Adapting Enumeration to Iterator.
* Adapter EnumeratorIterator implements Iterator to look like an Iterator
*/

public class EnumeratorIterator implements Iterator{
Enumeration enumeration;

public EnumeratorIterator(Enumeration enumeration){
this.enumeration = enumeration;
}

// Iterator's hasNext() method is delegated to Enumerator's hasMoreElements()
public boolean hasNext(){
return enumeration.hasMoreElements();
}

// Iterator's next() method is delegated to Enumerator's nextElement()
public Object next(){
return enumeration.nextElement();
}

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


How can Client use Adapter:
1. The Client makes a request to the adapter by calling a method on it using the target interface.
2. The Adapter translates that request into one or more calls on adaptee using adaptee interface.
3. The client receives the result of the call and never knows there is an adapter doing the translation.


Adapter Pattern using inheritance

Class Adapters : Class adapters use multiple inheritance to achieve their goals. As in the object adapter, the class adapter inherits the interface of the client's target. However, it also inherits the interface of the adaptee as well. Since Java does not support true multiple inheritance, this means that one of the interfaces must be inherited from a Java Interface type. Note that either or both of the target or adaptee interfaces could be an Java Interfaces. The request to the target is simply rerouted to the specific request that was inherited fro the adaptee interface.

Differnce between Object Adapters and Class Adapters
1. As Object Adapter uses composition it can not only adapt an adaptee class, but any of its subclasses. It is flexible.
2. Class Adapter is commited to only one adaptee. But again it has an advantage as no need to implement the entire adaptee. It can just override the behaviour of adaptee and also can override the behaviour as it is subclassing.
3. Note that class adapters have a problem with name conflicts if methods of the same signature exist on both the target and the adaptee. Note that just because two objects have methods that have the same signature (syntax), it does not guarantee that the two methods have the same meaning or behavior (sematics). That is, the two methods do not necessarily map directly to each other. Object adapters do not have this problem.
4. Class adapters are simpler than object adapters in that they involve fewer classes and are useful if total decoupling of the client and adaptee is not needed.

Why should I use Adapter Pattern:
1. Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application.
2. We can not change the library interface, since we may not have its source code.
3. Even if we did have the source code, we probably should not change the library for each domain-specific application.
4. You don’t want your object models implementing JavaVM specific interfaces becuase they might change in the future.
When to use Adapter Pattern:
Use the Adapter pattern when
1. You want to use an existing class, and its interface does not match the one you need.
2. You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces.

Some of the good OO design principles behind Adapter Pattern:
1. We use object composiition to wrap adaptee with an altered interface. This approach has an added advantage that we can use an adapter with any subclass of adaptee.
2. Pattern binds the client to an interface but not to implementation. We could use several adapters, each converting a different backend set of classes or we could add new implementations after the fact, as long as they adhere to target interface.

Two-way Adapter
A two-way adapter supports both the Target and the Adaptee interface. It allows an adapted object (Adapter) to appear as an Adaptee object or a Target object.
One way to implement two-way adapters is to use multiple inheritance, which can't be done in Java.
But we can have our adapter class implement two different Java interfaces. So the adapter can act as a Old Interface or New Interface.

Comparing Adapter Pattern with other Patterns:
1. Adapter converts one interface to another, Decorator doesn't alter interface but adds responsibility. Facade makes an interface simpler.
Decorator is thus more transparent to the application than an adapter is. As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters.
2. Adapters allows client to make use of libraries and subsets without changing any code. Decorators allow new behaviour to be added to the classes with out altering the existing code.
3. Adapter make things work after they're designed, Bridge makes them work before they are.
4. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
5. Adapter provides a different interface to its subject. Proxy provides the same interface. Decorator provides an enhanced interface.
6. Facade defines a new interface, whereas Adapter reuses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one.

Adapter pattern example in java
java.io.InputStreamReader(InputStream)
java.io.OutputStreamWriter(OutputStream)