作者qrtt1 (愚者)
站内java
标题Re: [问题] 不同class之间的传值取用
时间Thu Jul 13 21:42:48 2006
==站内信件==
转信又不正常了>"<
只好重po了
===============================================================
这不会没深度啊:)
这看起来很适合使用观察者模式
也刚好java本身就有这样的工具呦
我试着依您的架构写了一个sample
A_________________________________________________
import java.util.Observable;
public class A extends Observable{
int x = 0;
int y = 0;
public A() {
}
private void changeLocation(int x, int y){
this.x += x;
this.y += y;
// mark data have been changed
setChanged() ;
// notify observer
notifyObservers();
}
public void up() {
System.out.println("Up");
this.changeLocation(0,1);
}
public void down() {
System.out.println("Down");
this.changeLocation(0,-1);
}
public void left() {
System.out.println("Left");
this.changeLocation(-1,0);
}
public void right() {
System.out.println("Right");
this.changeLocation(1,0);
}
}
B__________________________________________________
import java.util.Observable;
import java.util.Observer;
public class B implements Observer {
private int x;
private int y;
public B(Observable o) {
o.addObserver(this);
}
public void update(Observable o, Object arg) {
if (o instanceof A) {
A a = (A) o;
this.x = a.x;
this.y = a.y;
}
display();
}
public void display() {
System.out.println("X: " + x);
System.out.println("Y: " + y);
}
}
TestIt______________________________________________________
import java.util.Random;
public class TestIt {
public static void main(String[] args) {
A playDevice = new A();
B display = new B(playDevice);
Random r = new Random();
for (int i = 0; i < 10; i++)
switch (r.nextInt() % 4) {
case 0:
playDevice.up();
break;
case 1:
playDevice.down();
break;
case 2:
playDevice.right();
break;
case 3:
playDevice.left();
break;
}
}
}
==================================================
Up
X: 0
Y: 1
Up
X: 0
Y: 2
Up
X: 0
Y: 3
Left
X: -1
Y: 3
Right
X: 0
Y: 3
Up
X: 0
Y: 4
Left
X: -1
Y: 4
Up
X: -1
Y: 5
Down
X: -1
Y: 4
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 163.26.34.105
※ 编辑: qrtt1 来自: 163.26.34.105 (07/14 04:42)