public class A {
private static A a = new A();
private int num1 = 0;
private int num2 = 0;
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
private A(){}
public static A getInstance(){
return a;
}
}
public class B {
private A a = A.getInstance();
//下面的構造方法可以解決我的問題
public B(){
setNum1();
setNum2();
}
public void setNum1(){
a.setNum1(2);
}
public void setNum2(){
a.setNum2(3);
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
}
public class C {
public static void main(String[] args) {
B b = new B();
A a = b.getA();
b.setNum1(); //行1
b.setNum2(); //行2
int num1 = a.getNum1();//行3
int num2 = a.getNum2();//行4
System.out.println(num1);
System.out.println(num2);
}
}
怎麼設計可以省去行1 和行2,在行3和行4執行的時候分別調用行1和行2?
public class A {
private static A a = new A();
private B b;
private int num1 = 0;
private int num2 = 0;
public void setB(B b) {
this.b = b;
}
public int getNum1() {
b.setNum1();
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
b.setNum2();
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
private A() {
}
public static A getInstance() {
return a;
}
}
public class B {
private A a = A.getInstance();
{
a.setB(this);
}
public void setNum1() {
a.setNum1(2);
}
public void setNum2() {
a.setNum2(3);
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
a.setB(this);
}
}
public class C {
public static void main(String[] args) {
B b = new B();
A a = b.getA();
int num1 = a.getNum1();// 行3
int num2 = a.getNum2();// 行4
System.out.println(num1);
System.out.println(num2);
}
}
最後不得不說,這個設計很不雅觀