简体   繁体   中英

Does the singleton pattern make sense for a Socket?

I have a Java application in which I have a socket. Now it's very important that only one socket is open at any point. I figure that a good way to ensure this is to create a wrapper class that enforces the singleton property on a Socket instance. For clarification: by singleton pattern I am referring to 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 idea of a singleton socket makes sense conceptually. The Socket will need to be able to reconnect and disconnect at any point throughout the course of the program and I'm not sure if that is possible with a singleton.

As far as I can tell this is not possible although I am hoping that there is some trick to it or I am simply misunderstanding something.

Absolutely, why not? Singleton pattern applies when you need a unique instance of a class accesible in any point of the application.

In this case, your singleton wrapper could create an instance of the socket in the constructor and expose methods to manage the socket transparently for the rest of the application.

A pseudocode example could be:

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()
        // ...
    }

    // ...
}

I don't see that this really buys you anything: indeed it may just give you a false sense of security. It doesn't stop any other part of the application from calling new Socket(...). I would just go with a Socket as an instance member somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM