Re: [問題] 建構子的引數可以是物件嗎?
※ 引述《calais007 (淺水中)》之銘言:
: ※ 引述《tzuyy (..)》之銘言:
: : 小弟在上一行先宣告Department z = new Department();就可以編譯了。
: : 謝謝各位大大的幫忙。但是我小弟又延生出另一個新的問題,
: : 如果x和z物件互相參考的話怎麼辦?orz....
: : 在MainClass.java這樣寫:
: : public class MainClass {
: : public static void main(String[] args) {
: : Department z = new Department(x);
: : Student x = new Student(z);
: : }
: : }
: : 在Student.java這樣寫:
: : public class Student {
: : private Department major;
: : public Student(Department m){
: : this.setDepartment(m);
: : }
: : public Department getDepartment(){
: : return major;
: : }
: : public void setDepartment(Department m){
: : major = m;
: : }
: : }
: : 在Department.java這樣寫:
: : public class Department {
: : private Student studentname;
: : public Department(Student s){
: : this.setDepartment(s);
: : }
: : public Student getDepartment(){
: : return studentname;
: : }
: : public void setDepartment(Student s){
: : studentname = s;
: : }
: : }
: : 小弟想到的方法是這樣子的,
: : 在Student類別先增一個建構子,
: : public Student(){};
: : 然後在MainClass類別先宣告一個x物件,使z可以順利建立,
: : 然後再讓x的major屬性參考到z物件。
: : public class Student {
: : private Department major;
: : public Student(){};
: : public Student(Department m){
: : this.setDepartment(m);
: : }
: : public Department getDepartment(){
: : return major;
: : }
: : public void setDepartment(Department m){
: : major = m;
: : }
: : }
: : public class MainClass {
: : public static void main(String[] args) {
: : Student x = new Student();
: : Department z = new Department(x);
: : x.setDepartment(z);
: : }
: : }
: : 想請問各位大大有其它的方法嗎?謝謝。
: 互相要使用對方的Reference我不建議這樣丟
: 丟到後來會不知道那個引數是從那丟來的
: 我建議採用Mediator Design Pattern來做
: http://www.patterndepot.com/put/8/Behavioral.html
GUI的程式設計中,一個事件伴隨著狀態的改變,要使這些component
了解目前的狀態來改變另一個component往往需要傳遞大量的referrence
這個時候使用Mediator Design Pattern來做是好的
但是原問題並沒有這麼複雜
只是 A 決定 B,B 又決定 A 這樣的 symmetric dependency 而已
所以並不需要使用Mediator Design Pattern
我認為比較好的解法是
public class Student {
public Student() {}
public void setDepartment(Department d) { this.d = d; }
private Department d;
}
public class Department {
public Department() {}
public void setStudent(Student s) { this.s = s; }
private Student s;
}
public class Main {
public static void main(String args[]) {
Student s = new Student();
Department d = new Department();
s.setDepartment(d);
d.setStudent(s);
}
}
如果語法有錯的話,請恕我目前無法使用編譯器
若有更好的解決方法,還望板友能不吝指教
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.115.205.85
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 7 之 7 篇):