Thursday, September 3, 2009

InetAddress and Factory Design Pattern

I was recently working on a project which required me to check if a server is reachable or not. I started looking at java.net.InetAddress.isReachable(int) to solve my problem. The javadoc was not very clear and so I went in to see how it was actually implemented. In the java file I came across Factory design pattern for creating Internet address(InetAddress), so I decided to blog about it.

One cannot create the InetAddress objects by invoking the constructor. One has to use static methods like getLocalHost() etc. Based on the type of IP address of the host i.e. whether it is version4 or version6 IP address, a Inet4Address or Inet6Address is returned by the factory. Both these classes extend InetAddress. This is transparent to the client, so the client need not worry about which type of InetAddress to create.

In brief, the factory design pattern delegates the responsibility of creating the correct object to the factory. The factory makes the decision of which class of object to construct based on the user input or some other implicit criteria(here it was IP address type).

Here is the snippet from the code in InetAddress.java which uses Factory Design Pattern to acheive it. In this code the factory is InetAddressImplFactory which makes the decision to either load(call constructor of) the Inet4Address class or Inet6Address class.

public class InetAddress implements java.io.Serializable {

............
static {

...............
impl = (new InetAddressImplFactory()).create();
...........
}

.........
}


class InetAddressImplFactory {

//create v6 or v4 address
static InetAddressImpl create() {
Object o;
if (isIPv6Supported()) {
o = InetAddress.loadImpl("Inet6AddressImpl");
} else {
o = InetAddress.loadImpl("Inet4AddressImpl");
}
return (InetAddressImpl)o;
}

............

}



No comments:

Post a Comment