user1958067
user1958067

Reputation: 81

Java simplify code

i have a beginners question:

I have 3 Classes extending Thread. They are doing the same job: open a ServerSocket and then wait for connections in a while loop. The only difference between these classes is, that they start a specific Thread when they have a connection. I want to simplify this and have one Class doing the job, that atm 3 classes are doing. In the example the only difference is the call of SocketThread1, SocketThread2 and SocketThread3.

How could i make 1 class instead of having 3 of them?

Example:

\\class 1

public void run()
{
    while(true)
    {
        Socket s = serversocket.accept();
        new SocketThread1(s).start();
    }}

\\class 2

public void run()
{
    while(true)
    {
        Socket s = serversocket.accept();
        new SocketThread2(s).start();
    }


}

\\class 3

public void run()
{
    while(true)
    {
        Socket s = serversocket.accept();
        new SocketThread3(s).start();
    }

Upvotes: 0

Views: 120

Answers (2)

iberbeu
iberbeu

Reputation: 16205

Why not to implement an Interface (or parent class) for SocketThread 1,2 and 3 and then pass just an instance of this interface and call its start() method?

EDIT: I mean something like this: (the code is not tested and should be adapted to your requirements)

public class SocketThread1 implements SocketThread{...}
public class SocketThread2 implements SocketThread{...}
public class SocketThread3 implements SocketThread{...}
public class YourClass implements Runnable{
private SocketThread thread;
public YourClass(SocketThread thread){
    this.thread = thread;
}
public void run()
{
thread.start();
}
}

Upvotes: 1

Eyal Schneider
Eyal Schneider

Reputation: 22446

You can have one Server class, that receives a SocketThreadFactory in the constructor.

Alternatively, the Server can be abstract, where subclasses should implement the createClientHandlerThread(Socket) method:

public abstract class Server extends Thread {
    private ServerSocket serverSocket;

    public Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void run() {
        try {
            while (true) {
                Socket s = serverSocket.accept();
                createClientHandlerThread(s).start();
            }
        } catch (IOException e) {
            // TODO: handle the exception
        }

    }

    protected abstract Thread createClientHandlerThread(Socket s);
}

Now define three (or more) simple subclasses, that only deal with the creation of the thread for a given socket.

Upvotes: 0

Related Questions