This is basicly a simple producer - consumer application. The code example is the following:
public class MyMainClass extends Application {
// blocking queue that will be shared among my prcesses
BlockingQueue bq;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
// parameters I wont the Thread passes to the server socket
TextArea parameters = new TextArea("parameters-for-the-server");
// setting the Producer button
Button btnProducer = new Button();
btnProducer.setText("Start Producer");
btnProducer.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/* ReadSocket connects to a web sockets,
reads strings and saves them into a shared blocking queue: bq*/
ReadSocket rs = new ReadSocket(bq);
new Thread(rs).start();
}
// setting the Consumer button
Button btnConsumer = new Button();
btnConsumer.setText("Start Consumer");
btnConsumer.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
/* ReadSocket connects to a web sockets,
reads strings and saves them into a shared blocking queue: bq*/
Consumer c = new Consumer(bq);
new Thread(c).start();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}
My professor said that I should pass values in the constructor if I want them to be available to other objects.
My ReadSocket
should look like something like this:
public class ReadSocket{
BlockingQueue bq;
ReadSocket(bq){
this.bq = bq;
// more code
}
/*I need here parameters in order to create an object o
that will be used to create another object ms*/
MyObject o = new MyObjext("parameters-for-the-server");
MyServer ms = new MyServer(o);
}
So, does it mean I have to pass my values like:
ReadSocket rs = new ReadSocket(bq, parameters.getText());
even if the ReadSocket
is not using them directly but creates an object based on parameters
? Is this correct to do?
Is there any other better way?
There are two ways you can do this. One using constructor
and other using setter method
. But as you mention that your professor suggested you to pass parameters using constructor so that these parameter are available to other objects.
Just make sure that you are storing reference to the parameters passed via constructor
public class ReadSocket{
BlockingQueue bq;
String parameters;
ReadSocket(BlockingQueue bq, String parameters)
{
this.bq = bq;
this.parameters = parameters;
}
private void createOtherObjects()
{
MyObject o = new MyObjext(this.parameters);
MyServer ms = new MyServer(o);
}
}