简体   繁体   中英

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 ?

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.

Actually, it's an example of an Abstract Factory Pattern . We know it's the abstract version of the pattern, because the return type is abstract (you could get either a Inet4Address or Inet6Address )

With this pattern, the conditional statements ( if s) are unavoidable and have to go somewhere, so it's fine. "Design nazi's" can go jump.

Often switches can be avoided by a good design, but sometimes there is no other option. Like to parse input that has been inserted from outside of the system (mostly by users). But for input that comes from your own system you should consider a better design or a method for each kind of input (if possible).

For instance, in this case, if you know if you are dealing with an IPv4 or IPv6 address you should be able to call the approperiate method instead of going to the factory. It would be bad design if only the factory method was available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM