zoukankan      html  css  js  c++  java
  • 简单的对象监听器 观察者设计模式

    该代码实现了一个可以注册监听类的类,如果注册了监听类,那么在类的一个方法执行前会执行监听类的方法。并且该监听类方法的参数就是被监听对象。

    监听类就是事件监听器,被监听对象就是事件源,事件监听器的参数就是事件对象。

    //设计一个事件源,被监听器监听  Observer(观察者设计模式)

    public class Demo2 {

           public static void main(String[] args) {

                 

                  Person p = new Person();

                  p.registerListener(new PersonListener(){

                         public void doeat(Event e) {

                                Person p = e.getSource();

                                System.out.println(p + "吃个死");

                         }

                         public void dorun(Event e) {

                                // TODO Auto-generated method stub

                         }

                        

                  });

                  p.eat();

           }

    }

    class Person{

          

           private PersonListener listener;

          

           public void eat(){

                  if(listener!=null){

                         listener.doeat(new Event(this));

                  }

           }

          

           public void run(){

                  if(listener!=null){

                         listener.dorun(new Event(this));

                  }

           }

          

           public void registerListener(PersonListener listener){

                  this.listener = listener;

           }

    }

    interface PersonListener{

          

           public void doeat(Event e);

          

           public void dorun(Event e);

          

    }

    class Event{

          

           private Person source;

           public Event() {

                  super();

                  // TODO Auto-generated constructor stub

           }

           public Event(Person source) {

                  super();

                  this.source = source;

           }

           public Person getSource() {

                  return source;

           }

           public void setSource(Person source) {

                  this.source = source;

           }

          

    }

  • 相关阅读:
    关于hive Metadata 使用 MsSQL
    hdp 2.06 安装备忘
    对于自我管理 ObjectContextManager的测试
    关于 Linq to EF 的内存泄漏问题
    使用过多的递归出现错误,“System.StackOverflowException”类型的未经处理的异常在 mscorlib.dll 中发生
    PowerShell 如何 远程连接【转】
    win7系统浏览器老是自动弹出网页怎么办
    win10如何深度清理C盘
    Win7电脑系统崩溃怎么解决?
    win7磁盘打不开如何解决
  • 原文地址:https://www.cnblogs.com/flying607/p/3469133.html
Copyright © 2011-2022 走看看