1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65 |
import java.util.ArrayList; public class Observer_Subject { /** * @param args 观察者模式 */ public
static void main(String[] args) { // TODO Auto-generated method stub Cat cat= new
Cat(); Mouse mouse= new
Mouse(cat); People people= new
People(cat); cat.cry(); } } //通知者 interface
Subject{ void
AddObserver(Observer obj); } //猫实现了通知者的接口 class
Cat implements
Subject{ ArrayList<Observer> arrayList; public
Cat() { arrayList= new
ArrayList<Observer>(); } @Override public
void AddObserver(Observer obj) { // TODO Auto-generated method stub arrayList.add(obj); } void
cry(){ //猫叫,通知所有的观察者 for
(Observer obj:arrayList) { obj.responer(); } } } //观察者 interface
Observer{ void
responer(); } class
Mouse implements
Observer{ public
Mouse(Cat c) { //将当前的观察者加入到集合中 c.AddObserver( this ); } @Override public
void responer() { // TODO Auto-generated method stub System.out.println( "老鼠跑" ); } } class
People implements
Observer{ public
People(Cat c) { c.AddObserver( this ); } @Override public
void responer() { // TODO Auto-generated method stub System.out.println( "人醒了" ); } } |
原文:http://www.cnblogs.com/daifei/p/3689017.html