观察者模式

来源:互联网 发布:php开源库存管理系统 编辑:程序博客网 时间:2024/05/17 03:50

    相信每个人在高中的时候在自习课的时候都有偷偷的玩过手机,而且 绝大部分的高中都不让学生带手机,更不用说上课玩了。所以每个人在玩的时候总是找同桌或者附近的同学帮忙看着 如果老师来了 就提醒自己一下。个人感觉这个场景跟观察者模式很像。接下来我们用java代码 简单的实现一下。

首先我们将 老师来了 同学们要做的动作抽象为一个接口

public interface IAction {public abstract void doSomeTing();}

然后我们写一个玩手机的同学类,并且实现楼上的接口

public class PlayPhoneStudent implements IAction{private String studentName;PlayPhoneStudent(String studentName){this.studentName = studentName;}@Overridepublic void doSomeTing() {System.out.println(studentName+"赶快放下手机,装作认真学习的样子");}}

接下来 我们在写一个 观察老师来没来的同学类

public class ObserverStudent {private String studentName;ObserverStudent(String studentName){this.studentName =studentName;}//用来保存 在玩手机 并且叫该名同学观察老师来没来的同学private  List<IAction> playerPhoneStudents = new ArrayList<>();public void addPlayPhoneStudent (IAction playPhoneStudent) {playerPhoneStudents.add(playPhoneStudent);}//老师来了 通知每一个 托我们观察老师的同学public void tellTeacherCome() {for (IAction iAction : playerPhoneStudents) {iAction.doSomeTing();}}}


最后写一个测试类

public class Test {public static void main(String[] args) {//首先我们先实例化3个玩手机的同学 一个不玩手机的同学PlayPhoneStudent s1 = new PlayPhoneStudent("s1");PlayPhoneStudent s2 = new PlayPhoneStudent("s2");PlayPhoneStudent s3 = new PlayPhoneStudent("s3");ObserverStudent noPlayPhoneStudent = new ObserverStudent("GoodStudent");//接下来 3个玩手机的同学怕玩手机被老师看到,所以叫不玩手机的那个同学帮忙看着老师来没来noPlayPhoneStudent.addPlayPhoneStudent(s1);noPlayPhoneStudent.addPlayPhoneStudent(s2);noPlayPhoneStudent.addPlayPhoneStudent(s3);//过了一段时间 老师来了。。noPlayPhoneStudent.tellTeacherCome();}}