Does a single template make sense for Socket?

I have a Java application in which I have a socket. Now it is very important that only one socket is open at any point. I believe that a good way to ensure this is to create a wrapper class that will use the singleton property in the instance Socket. To clarify: by the singleton pattern, I mean the following generic class design:

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    //Private constructor prevents instantiating and subclassing
    private Singleton(){ }

    //Static 'instance' method
    public static Singleton getInstance( ) {
         return INSTANCE;
    }
    //...Other class methods
}

I am wondering if the concept of a singleton socket makes sense conceptually. SocketI will have to be able to reconnect and disconnect at any time throughout the program, and I'm not sure if this is possible using a single singlet.

As far as I can tell, this is not possible, although I hope there is some kind of trick or I just misunderstand something.

+3
2

, ? Singleton , , .

singleton .

:

public class SocketDevice{

    private static final SocketDevice INSTANCE = new SocketDevice();

    private Socket socket;

    //Private constructor prevents instantiating and subclassing
    private SocketDevice(){ 
        // instanciates the socket ...
    }

    //Static 'instance' method
    public static SocketDevice getInstance( ) {
         return INSTANCE;
    }

    public void open(){
        // ...
        socket.open()
        // ...
    }

    public void close(){
        // ...
        socket.close()
        // ...
    }

    // ...
}
+3

, : , . Socket (...). Socket -.

+1

All Articles