Search code examples
javaoopdesign-patternsfactory-patterninetaddress

Is the static method getByname of InetAddress class in java an example of Factory method pattern?


The standard factory Method design pattern talks of 4 classes. Creator,Product n their concrete implementations.

So for each product we need to instantiate corresponding factory which has methods to create the product.

But I have also seen scenarios where people declare constructor as private and have a static method that creates an object of the same class. Something similar to what we do with singletons.

For example getByname is one of the static methods of InetAddress that returns one of its subclass depending upon whats the parameter. and people call it factory method.

Is this also an example of factory method pattern ? does it contain if-else-if inside the method to decode the parameter or switch statement ? But isnt use of switch n conditional statements considered a bad OO design practice ?


Solution

  • Yes, this is an example of the factory method pattern.

    Ans yes, it parses its argument and decides which kind of address (which subclass) to instantiate (this is easily findable by looking at the source code of the method, which comes with the JDK).

    At some point, you have to use conditional statements. It's not necessarily bad practice. In this case, the factory method is precisely there to encapsulate the address parsing and return the appropriate subclass, rather than having to do it in the caller. What would be bad OO practice would be to be forced to write:

    int addressType = InetAddress.getAddressType(address);
    InetAddress ia = null;
    switch (addressType) {
        case V4 : 
            ia = new Inet4Address();
            break;
        case V6 : 
            ia = new Inet6Address();
            break;
        default :
            throw new RuntimeException("bad address");
    }
    

    Instead, this logic is encapsulated into the factory method.