Java – is this class single?
Are the categories listed below singles? Since the constructor is declared public, can I infer that the class is a singleton of the wrong 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; } }
Solution
You can make it single, but you need to find another way to inject the simulator into it
In the current implementation, the simulator is set the first time someone calls the constructor This constructor is very strange because it sets a static field It also immediately opens a connection, separate from the connection used by the singleton instance
If the getInstance () method is called before the constructor calls at least once, the emulator will never be set up.
To make it a suitable singleton, you can delete the constructor and add a private parameterless constructor You also need a static setSimulator () method to set up the static field and make sure that it is invoked before any other interaction with the simulator is required.
If you have dependencies between singletons, I suggest you use the inversion of control mode, where the IOC container creates service objects and connects them together