首页 > 代码库 > 设计模式01观察者模式(java)
设计模式01观察者模式(java)
1 import java.util.Map; 2 import java.util.HashMap; 3 import java.util.Observer; 4 import java.util.Observable; 5 6 //学生类(Student)继承Observable后变得可以被观察 7 class Student extends Observable{ 8 //属性 9 private String name; 10 private boolean isSleep = false; 11 private boolean isLate = false; 12 //构造函数 13 public Student(){} 14 public Student(String name){ 15 this.name = name; 16 } 17 //睡觉行为 18 public void sleep(){ 19 System.out.println(name + " is sleeping"); 20 isSleep = true; 21 setChanged(); 22 notifyObservers("sleep"); 23 24 } 25 //迟到行为 26 public void late(){ 27 System.out.println(name + " was lated"); 28 isLate = true; 29 setChanged(); 30 notifyObservers("late"); 31 } 32 } 33 //教师类(Teacher)实现Observer接口成为观察者 34 class Teacher implements Observer{ 35 //参数arg作为key,该参数触发的回应作为value存储在Map中 36 private Map<String,String> info = new HashMap<String,String>(); 37 public Teacher(){ 38 info.put("sleep","wakeup!wakeup!"); 39 info.put("late","come in."); 40 } 41 //添加键值对 42 public boolean addSay(String k,String v){ 43 return info.put(k,v)==null?false:true; 44 } 45 @Override 46 public void update(Observable o,Object arg){ 47 String say = info.get(arg); 48 if(say == null){ 49 return; 50 } 51 System.out.println("teacher: "+say); 52 } 53 } 54 //班主任类(ClassHead)实现Observer接口成为观察者 55 class ClassHead implements Observer{ 56 private Map<String,String> info = new HashMap<String,String>(); 57 public ClassHead(){ 58 info.put("sleep","goOutWashBaFace"); 59 info.put("late","cleanTheRoom!"); 60 } 61 public boolean addSay(String k,String v){ 62 return info.put(k,v)==null?false:true; 63 } 64 @Override 65 public void update(Observable o,Object arg){ 66 String say = info.get(arg); 67 if(say == null){ 68 return; 69 } 70 System.out.println("classHead: "+say); 71 } 72 } 73 public class ObserverDemo{ 74 public static void main(String[] arguments){ 75 Student tom = new Student("Tom"); 76 tom.addObserver(new ClassHead()); 77 tom.addObserver(new Teacher()); 78 79 System.out.println("有 "+tom.countObservers()+" 个观察者在观察Tom"); 80 tom.sleep(); 81 tom.late(); 82 } 83 }
设计模式01观察者模式(java)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。