精華區beta OOAD 關於我們 聯絡資訊
==站內信件== 轉信又不正常了>"< 只好重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)