Is this class single?

Is the class lower than one single? Since the constructor is declared as open, can I conclude that the class is a single with an incorrect implementation?

public class CreateDevice extends Functionality{ private static Simulator simulator; ConnectionDB connect = ConnectionDB.getInstance(); public CreateDevice(Simulator simulator){ this.simulator = simulator; } private static CreateDevice instance; synchronized public static CreateDevice getInstance() { if(instance == null){ instance = new CreateDevice(simulator); } return instance; } } 
+6
source share
3 answers

You can make it single, but then you need to find another way to insert a simulator into it.

In the current implementation, the simulator is installed for the first time when someone calls the constructor. This constructor is very strange because it sets a static field. It will also immediately open the connection, separate from the connection used by the singleton instance.

If the getInstance () method is called before the constructor is called at least once, the simulator will never be set.

To make it suitable single, you can remove the constructor and add the private no-args constructor. You will also need the static setSimulator () method, which sets the static field and will invoke it before any other interaction with the simulator is required.

If you have dependencies between singletones, I would recommend switching to the Inversion-of-Control pattern, where the IoC container creates the service objects and connects them together.

+1
source

In a word - no. Since the constructor is public , anyone can create a new instance of it wherever they want. Creating a private constructor should solve the problem and turn the class into a singleton.

+7
source

I would say that you correctly say that this will not be Singleton in the current implementation.

Either you need to make the constructor private (which is usually done), or if you need a public constructor for obsolete reasons, you must create a constructor that checks if the instance is null and throws an exception if it already exists or creates it, calling another private constructor by assigning it to an instance and returning it. The first option is preferable, while the other works fine for most projects where the refactor is too expensive.

+2
source

Source: https://habr.com/ru/post/1012752/


All Articles