转自:http://zhangjunhd.blog.51cto.com/113473/68949
在Java中通过Observable类和Observer接口实现了观察者模式。Observer对象是观察者,Observable对象是被观察者。
void addObserver(Observer o)
|
setChanged();
notifyObservers();
|
void update(Observable o, Object arg)
|
package
com.zj.observer;
import
java.util.Observable;
public
class
NumObservable
extends
Observable {
private
int
data
= 0;
public
int
getData() {
return
data
;
}
public
void
setData(
int
i) {
data
= i;
setChanged();
notifyObservers();
}
}
|
package
com.zj.observer;
import
java.util.Observable;
import
java.util.Observer;
public
class
NumObserver
implements
Observer{
public
void
update(Observable o, Object arg) {
NumObservable myObserable=(NumObservable) o;
System.
out
.println(
"Data has changed to "
+myObserable.getData());
}
}
|
package
com.zj.observer;
public
class
SingleTest {
public
static
void
main(String[] args) {
NumObservable number =
new
NumObservable();
number.addObserver(
new
NumObserver());
number.setData(1);
number.setData(2);
number.setData(3);
}
}
|
package
com.zj.observers;
import
java.util.Observable;
public
class
NumsObservable
extends
Observable {
public
final
static
Integer
ODD
= 1;
public
final
static
Integer
EVEN
= 2;
private
int
data
= 0;
public
int
getData() {
return
data
;
}
public
void
setData(
int
i) {
data
= i;
Integer flag =
EVEN
;
if
((
data
& 0x0001) == 1)
flag =
ODD
;
setChanged();
notifyObservers(flag);
}
}
|
package
com.zj.observers;
import
java.util.Observable;
import
java.util.Observer;
public
class
OddObserver
implements
Observer {
public
void
update(Observable o, Object arg) {
if
(arg == NumsObservable.
ODD
) {
NumsObservable myObserable = (NumsObservable) o;
System.
out
.println(
"OddObserver:Data has changed to "
+ myObserable.getData());
}
}
}
|
package
com.zj.observers;
import
java.util.Observable;
import
java.util.Observer;
public
class
EvenObserver
implements
Observer {
public
void
update(Observable o, Object arg) {
if
(arg == NumsObservable.
EVEN
) {
NumsObservable myObserable = (NumsObservable) o;
System.
out
.println(
"EvenObserver:Data has changed to "
+ myObserable.getData());
}
}
}
|
package
com.zj.observers;
public
class
MultiTest {
public
static
void
main(String[] args) {
NumsObservable number =
new
NumsObservable();
number.addObserver(
new
OddObserver());
number.addObserver(
new
EvenObserver());
number.setData(1);
number.setData(2);
number.setData(3);
}
}
|