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;

           }

          

    }

  • 相关阅读:
    Windows打开软件老是弹出无法验证发布者
    SpringMvc接受特殊符号参数被转义
    时代更替中的方正
    你应该知道的c# 反射详解
    C#使用System.Data.SQLite操作SQLite
    C# 动态调用WebService
    C# API: 生成和读取Excel文件
    11个强大的Visual Studio调试小技巧
    .Net 垃圾回收和大对象处理
    Visual Studio原生开发的10个调试技巧(一)
  • 原文地址:https://www.cnblogs.com/flying607/p/3469133.html
Copyright © 2011-2022 走看看