想象一下你有一个聊天程序,你想在其中向服务器发送和接收数据。将客户端连接变成单例会很聪明吗?或者这会破坏数据流。
我的客户单例示例:
public class Client {
private static Client client;
private final int portNumber = 7070;
private Socket socket;
private Client(){
connect();
}
public static synchronized Client getClient(){
if (client == null) {
client = new Client();
}
return client;
}
public void connect(){
try {
InetAddress adr = InetAddress.getByName("localhost");
socket = new Socket(adr, portNumber);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}