What’s the difference between creating a Socket via Socketfactory and creating one with new Socket?

Asked

Viewed 89 times

2

I was studying about Sockets and saw that some people created sockets with Socketfactory (javax).

I’ve always created like this: Socket skt = new Socket(host, port);

In the example I was like this:

Socket s = SocketFactory.getDefault().createSocket(host, port);

What is the difference between these two ways of creating a socket?

1 answer

5


Factory Pattern

The basic difference is that in one you initialize the object with the new and with the other you use the Factory Pattern to take care of it for you.

Generally all Factory standards (Simple Factory, Factory Method, Abstract Factory) encapsulate the creation of objects. The Factory Method pattern in turn encapsulates the creation of objects, however the difference is that in this pattern encapsulates the creation of objects letting the subclasses decide which objects to create.

The Class Diagram below shows more details about how the Factory Method works.


(source: web-03.net)

In the class diagram above we have the abstract creator class that is the Creator that defines an abstract factory method that subclasses implement to create a product (factoryMethod) and can own one or more methods with their proper behaviors that will call the factoryMethod. Normally the factoryMethod method of Creator also has an abstract Product that is produced by a subclass (Concretecreator). Note that each Concretecreator will produce its own creation method.

According to the GOF (Group Of Four) the Factory Method standard is: "A pattern that defines an interface to create an object, but allows classes to decide which class to instantiate. The Factory Method allows a class to defer instantiation to subclasses".

Advantage of the Factory Pattern

With the standard Factory Method we can encapsulate the code that creates objects. It is very common to have classes that instantiate concrete classes and this part of the code usually undergoes several modifications, so in these cases we use a Factory Method that encapsulates this instantiation behavior.

Using the Factory Method we have our creation code in an object or method, thus avoiding duplication and in addition we have a unique place to do maintenance. The standard also gives us flexible and extensible code for the future.

Source: http://www.devmedia.com.br/padrao-de-projeto-factory-method-em-java/26348

Browser other questions tagged

You are not signed in. Login or sign up in order to post.