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;

           }

          

    }

  • 相关阅读:
    【后缀数组】
    【后缀数组之height数组】
    【后缀数组之SA数组】【真难懂啊】
    【转】为何浮点数可能丢失精度
    UVa_Live 3664(精度坑)
    【火车出栈】ZOJ
    并发查询
    java基础知识1
    感悟__你总是要建立自己的价值观,世界观,人生观,信念的,总不能一直靠鸡汤,被外界,环境,他人,见闻等所掌控你的情绪,积极或者消极.
    batch、随机、Mini-batch梯度下降
  • 原文地址:https://www.cnblogs.com/flying607/p/3469133.html
Copyright © 2011-2022 走看看