摘自:
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. 结构体位制 中存在 有符号 与 无符号 -- C

    #include <stdio.h> #include <stdlib.h> #include <string.h> /* 有符号 结构体1 */ struct b ...

  2. #pragma pack

    原文链接: http://www.cnblogs.com/s7vens/archive/2012/03/06/2382236.html pack 为 struct, union 和 class 等的成 ...

  3. Ubuntu下python两个版本的切换

    最近在Ubuntu16.04安装了python3.5还有系统自带的python2.7.13,总结一下不同版本的切换问题. alias:别名 bashrc:个人配置文件 一.修改Python版本(针对用 ...

  4. 数据库分享一: MySQL的Innodb缓存相关优化

    无论是对于哪一种数据库来说,缓存技术都是提高数据库性能的关键技术,物理磁盘的访问速度永 远都会与内存的访问速度永远都不是一个数量级的.通过缓存技术无论是在读还是写方面都可以大大提 高数据库整体性能. ...

  5. linux io ports io memory

    http://m.blog.csdn.net/article/details?id=7204458

  6. 每日英语:Why Food Companies Are Fascinated by the Way We Eat

    Are you a cruncher? Or a 'smoosher'? cruncher:咬嚼者,咬碎 Some people crave the perfectly crispy crunch o ...

  7. asp.net 获取客户端IP

    一.名词 首先说一下接下来要讲到的一些名词. 在Web开发中,我们大多都习惯使用HTTP请求头中的某些属性来获取客户端的IP地址,常见的属性是REMOTE_ADDR.HTTP_VIA和HTTP_X_F ...

  8. 向linux服务器上传下载文件方式收集

    向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...

  9. 【Java】创建线程对象两种方式

    1.继承Thread类,重载run方法: Thread t = new Thread(new Runnable() { @Override public void run() { // TODO Au ...

  10. 使用嵌入文档Here Documents

    Unix/Linux Shell编程实战:使用嵌入文档Here Documents 一.Here Documents(嵌入文档)Here Documents作为重定向的一种方式,指示shell从源文件 ...