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;

           }

          

    }

  • 相关阅读:
    爬取校园新闻首页的新闻
    网络爬虫基础练习
    综合练习:词频统计
    免费的论文查重网站
    Hadoop综合大作业
    理解MapReduce
    熟悉常用的HBase操作
    熟悉常用的HDFS操作
    爬虫大作业
    数据结构化与保存
  • 原文地址:https://www.cnblogs.com/flying607/p/3469133.html
Copyright © 2011-2022 走看看