這基本上是一個簡單的生產(chǎn)者-消費者應(yīng)用程序。代碼示例如下: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(); }}我的教授說,如果我希望它們可用于其他對象,我應(yīng)該在構(gòu)造函數(shù)中傳遞值。我ReadSocket應(yīng)該看起來像這樣:public class ReadSocket{ BlockingQueue bq; ReadSocket(bq){ this.bq = bq; // more code }那么,這是否意味著我必須傳遞我的價值觀,例如:ReadSocket rs = new ReadSocket(bq, parameters.getText()); 即使ReadSocket不是直接使用它們而是基于parameters? 這樣做正確嗎?還有其他更好的方法嗎?
1 回答

蠱毒傳說
TA貢獻1895條經(jīng)驗 獲得超3個贊
有兩種方法可以做到這一點。一個使用constructor和其他使用setter method。但是正如您提到的,您的教授建議您使用構(gòu)造函數(shù)傳遞參數(shù),以便其他對象可以使用這些參數(shù)。
只要確保您存儲對通過構(gòu)造函數(shù)傳遞的參數(shù)的引用
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
提交
取消