What's the difference between creating a Socket via SocketFactory and creating one with new Socket?

1

I was studying on Sockets and saw that some people were creating sockets with SocketFactory (javax).

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

In the example it looked like this:

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

What is the difference between these two ways to create a socket?

    
asked by anonymous 12.10.2015 / 21:17

1 answer

4

Factory pattern

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

In general, all Factory (Factory Factory, Factory Factory, and Factory Factory) encapsulate the creation of objects. The Factory Method pattern in turn encapsulates object creation, however, the difference is that in this pattern it encapsulates object creation by letting subclasses decide which objects to create.

The Class Diagram below shows more details about the operation of the Factory Method pattern.

link

In the class diagram above we have the abstract creator class that is the Creator that defines an abstract factory method that the subclasses implement to create a product (factoryMethod) and can own one or more methods with their due behaviors that will call the factoryMethod . Usually 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 method of creation.

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

Factory Pattern Advantage

With the Factory Method pattern we can encapsulate 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 those 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 we also have a unique place to do maintenance. The standard also gives us a flexible and extensible code for the future.

Source: link

    
12.10.2015 / 21:23