Friday, August 27, 2010

Session 5:Interface

One of the most interesting and intriguing concept that is an absolute necessity if you are to understand Object Orientation principles is an interface. The main usage is around re-usability and minimum change necessary when adhering to a contract.

What is it?

An interface is a contract. There may be several implementations of an interface.

Analogy:
I want to use a service provider for my tv.
I have paid BT and they deliver their "custom" set-top box to use.

In 6 months time I am fed up with BT and want to switch over to Sky.
Obviously I can't use the same set-top box and I have to pay for the sky set-top box.

What if I had one set-top box which spoke to all these providers?

And that is the interface. A set-top box which is a common contract for all service providers.
It is a specification/standard which has to be adhered by the service provider.

In language terms it is a service contract which provides specifications or method declarations.

Your service providers are to implement the interface and adhere to the contract, so that as a user of that service, switching over is easier and reduces complexity and cost.

Example:
Service:
public interface Jms{
public void storeMessage(String message);
public String getMessage();
}

ServiceProvider 1 [ActiveMQ]:
public class ActiveMQProvider implements Jms {
private Message message = new Message();
@Override
public void storeMessage(String message) {
message.store (message);
}

@Override
public String getMessage() {
return message.retrieve();
}
}

ServiceProvider 2 [IBM-MQ]:
public class IbmMQProvider implements Jms {

private String message;

@Override
public void storeMessage(String message) {
this.message = message;
}

@Override
public String getMessage() {
return this.message;
}
}

Service Client:

public class JmsClient {

public static void main(String args[]) {
useJmsService();
}

private static void useJmsService() {
Jms jms = new IbmMQProvider();
//To switch service: comment the previous line and un-comment the next line
//Jms jms = new ActiveMQProvider();
jms.sendMessage("Message in a bottle");
System.out.println(jms.getMessage());
}

}

Benefit:

The benefit/advantage is from the client's perspective. It is the user of these services who gains from it all. To switch services you dont have to re-do your entire Service Client code base. Just a change in ServiceProvider will do. Well that should be the aim anyway. Because in the real world nothing is too simple.

0 Comments:

Post a Comment

<< Home