这基本上是一个简单的生产者-消费者应用程序。代码示例如下: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(); }}我的教授说,如果我希望它们可用于其他对象,我应该在构造函数中传递值。我ReadSocket应该看起来像这样:public class ReadSocket{ BlockingQueue bq; ReadSocket(bq){ this.bq = bq; // more code }那么,这是否意味着我必须传递我的价值观,例如:ReadSocket rs = new ReadSocket(bq, parameters.getText()); 即使ReadSocket不是直接使用它们而是基于parameters? 这样做正确吗?还有其他更好的方法吗?
1 回答
蛊毒传说
TA贡献1895条经验 获得超3个赞
有两种方法可以做到这一点。一个使用constructor和其他使用setter method。但是正如您提到的,您的教授建议您使用构造函数传递参数,以便其他对象可以使用这些参数。
只要确保您存储对通过构造函数传递的参数的引用
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);
}
}
添加回答
举报
0/150
提交
取消