摘自:
http://www.ntu.edu.sg/home/ehchua/programming/java/J4a_GUI.html Creating Your Own Event, Source and Listener:
Suppose that we have a source called Light, with two states - on and off. The source is capable of notifying its registered listener(s), whenever its state changes. First, we define the LightEvent class (extends from java.util.EventObject).
Next, we define a LightListener interface to bind the source and its listeners. This interface specifies the signature of the handlers, lightOn(LightEvent) and lightOff(LightEvent).
In the source Light, we use an ArrayList to maintain its listeners, and create two methods: addLightListner(LightListener) and removeLightListener(LightListener). An method called notifyListener() is written to invoke the appropriate handlers of each of its registered listeners, whenever the state of the Light changes.
A listener class called LightWatcher is written, which implements the LightListener interface and provides implementation for the handlers. Event: LightEvent.java
/** LightEvent */
import java.util.EventObject; public class LightEvent extends EventObject {
public LightEvent (Object src) {
super(src);
}
} Listener Interface: LightListener.java
/** The LightListener interface */
import java.util.EventListener; public interface LightListener extends EventListener {
public void lightOn(LightEvent evt); // called-back upon light on
public void lightOff(LightEvent evt); // called-back upon light off
} Source: Light.java
/** The Light Source */
import java.util.*; public class Light {
// Status - on (true) or off (false)
private boolean on;
// Listener list
private List<LightListener> listeners = new ArrayList<LightListener>(); /** Constructor */
public Light() {
on = false;
System.out.println("Light: constructed and off");
} /** Add the given LightListener */
public void addLightListener(LightListener listener) {
listeners.add(listener);
System.out.println("Light: added a listener");
} /** Remove the given LightListener */
public void removeLightListener(LightListener listener) {
listeners.remove(listener);
System.out.println("Light: removed a listener");
} /** Turn on this light */
public void turnOn() {
if (!on) {
on = !on;
System.out.println("Light: turn on");
notifyListener();
}
} /** Turn off this light */
public void turnOff() {
if (on) {
on = !on;
System.out.println("Light: turn off");
notifyListener();
}
} /** Construct an LightEvent and notify all its registered listeners */
private void notifyListener() {
LightEvent evt = new LightEvent(this);
for (LightListener listener : listeners) {
if (on) {
listener.lightOn(evt);
} else {
listener.lightOff(evt);
}
}
}
} Listener: LightWatcher.java
/** An implementation of LightListener class */
public class LightWatcher implements LightListener {
private int id; // ID of this listener /** Constructor */
public LightWatcher(int id) {
this.id = id;
System.out.println("LightWatcher-" + id + ": created");
} /** Implementation of event handlers */
@Override
public void lightOn(LightEvent evt) {
System.out.println("LightWatcher-" + id
+ ": I am notified that light is on");
} @Override
public void lightOff(LightEvent evt) {
System.out.println("LightWatcher-" + id
+ ": I am notified that light is off");
}
} A Test Driver: TestLight.java
/** A Test Driver */
public class TestLight {
public static void main(String[] args) {
Light light = new Light();
LightWatcher lw1 = new LightWatcher(1);
LightWatcher lw2 = new LightWatcher(2);
LightWatcher lw3 = new LightWatcher(3);
light.addLightListener(lw1);
light.addLightListener(lw2);
light.turnOn();
light.addLightListener(lw3);
light.turnOff();
light.removeLightListener(lw1);
light.removeLightListener(lw3);
light.turnOn();
}
} Below are the expected output:
Light: constructed and off
LightWatcher-1: created
LightWatcher-2: created
LightWatcher-3: created
Light: added a listener
Light: added a listener
Light: turn on
LightWatcher-1: I am notified that light is on
LightWatcher-2: I am notified that light is on
Light: added a listener
Light: turn off
LightWatcher-1: I am notified that light is off
LightWatcher-2: I am notified that light is off
LightWatcher-3: I am notified that light is off
Light: removed a listener
Light: removed a listener
Light: turn on
LightWatcher-2: I am notified that light is on

java_Observer Design Pattern的更多相关文章

  1. 说说设计模式~大话目录(Design Pattern)

    回到占占推荐博客索引 设计模式(Design pattern)与其它知识不同,它没有华丽的外表,没有吸引人的工具去实现,它是一种心法,一种内功,如果你希望在软件开发领域有一种新的突破,一个质的飞越,那 ...

  2. 设计模式(Design Pattern)系列之.NET专题

    最近,不是特别忙,重新翻了下设计模式,特地在此记录一下.会不定期更新本系列专题文章. 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结. 使用 ...

  3. [转]Design Pattern Interview Questions - Part 4

    Bridge Pattern, Composite Pattern, Decorator Pattern, Facade Pattern, COR Pattern, Proxy Pattern, te ...

  4. [转]Design Pattern Interview Questions - Part 2

    Interpeter , Iterator , Mediator , Memento and Observer design patterns. (I) what is Interpreter pat ...

  5. [转]Design Pattern Interview Questions - Part 3

    State, Stratergy, Visitor Adapter and fly weight design pattern from interview perspective. (I) Can ...

  6. [转]Design Pattern Interview Questions - Part 1

    Factory, Abstract factory, prototype pattern (B) What are design patterns? (A) Can you explain facto ...

  7. design pattern

    1. visitor design pattern http://butunclebob.com/ArticleS.UncleBob.IuseVisitor

  8. Design Pattern: Observer Pattern

    1. Brief 一直对Observer Pattern和Pub/Sub Pattern有所混淆,下面打算通过这两篇Blog来梳理这两种模式.若有纰漏请大家指正. 2. Use Case 首先我们来面 ...

  9. Scalaz(10)- Monad:就是一种函数式编程模式-a design pattern

    Monad typeclass不是一种类型,而是一种程序设计模式(design pattern),是泛函编程中最重要的编程概念,因而很多行内人把FP又称为Monadic Programming.这其中 ...

随机推荐

  1. Python floor() 函数

    描述 floor(x) 函数返回一个小于或等于 x 的的最大整数(向下取整) 语法 以下是 floor() 方法的语法: import math math.floor( x ) 注意:floor()是 ...

  2. 使用国内镜像composer安装laravel

    1.安装 Laravel,创建blog项目 首先先说一下直接安装的方法,要想使用这个方法,首先要FQ(这是我们的基本国情决定的).这样的安装方式有两种: ①.全局安装 使用命令Laravel Inst ...

  3. 解决:IIS APPPOOL\DefaultAppPool 登录失败的问题

    为大家介绍下解决IIS APPPOOL\DefaultAppPool 登录失败的方法,有遇到类似问题的朋友参考下. 添加ASP.NET网站时,选择添加"添加应用程序"连接sql s ...

  4. 翻翻git之---效果鲜明的类ViewPager库 ConvenientBanner(对图片载入部分进行改动)

    转载请注明出处:王亟亟的大牛之路 昨天写了篇基础的View绘制的内容貌似观众老爷们不怎么喜欢.那再这里再安利下自己定义View时.用到Paint Canvas的一些温故.讲讲用路径绘画实现动画效果(基 ...

  5. 怎样设置linux中Tab键的宽度(可永久设置)

    和我的上篇文章一样,能够设置当前用户的Tab键宽度.也能够设置全部用户的Tab键宽度 一.仅设置当前用户的Tab键宽度 输入命令:vim ~/.vimrc 然后:set tabstop=4   //我 ...

  6. gulp自动化ES6转ES5

    npm install --save-dev gulp npm install --save-dev gulp-babel npm install --save-dev babel-preset-es ...

  7. Http请求中Content-Type讲解

    http://blog.csdn.net/weichuang_1/article/details/50451496 ****************************************** ...

  8. js实现新闻条目滚动效果

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. LeetCode: Word Break II 解题报告

    Word Break II Given a string s and a dictionary of words dict, add spaces in s to construct a senten ...

  10. Jar/War/Ear等包的作用与区别详解

    以客户角度来看,jar文件就是一种封装格式,用户不需要知道jar包中有多少个.class格式的文件及每个文件中的功能与作用,也可以得到相应的访问的结果.java中除了jar格式还有war和ear等包文 ...