摘自:
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. golang(5)使用beego 开发 api server 和前端同学拆分开发,使用swagger

    1,beego api Swagger 是一个规范和完整的框架,用于生成.描写叙述.调用和可视化 RESTful 风格的 Web 服务.整体目标是使client和文件系统作为服务器以相同的速度来更新. ...

  2. npm 模块化方式接入 font-awsome

    https://segmentfault.com/q/1010000009795785/a-1020000009796355 $ npm install font-awesome 在main.js里添 ...

  3. 安装ubuntu和windows双系统后,如何修改默认启动项

    在安装了Ubuntu16.04系统之后,系统会默认自启动Ubuntu16.04,而我们大多数情况下可能都在使用windows系统,不修改默认设置,不经意间便会启动了Ubuntu16.04,通过我的经历 ...

  4. linux中init.d文件夹的说明

    一.简单说明 /etc/init.d 是 /etc/rc.d/init.d 的软链接(soft link).可以通过 ll 命令查看. ls -ld /etc/init.d lrwxrwxrwx. r ...

  5. Latex中文utf-8编码的三种方式

    我们知道Latex一般用CJK和CTEX宏包支持中文编辑,CJK和CTEX的默认编码是GBK,而windows下的默然编码就是GBK,因此CJK和CTEX不需要特殊配置就可以直接支持中文Latex编译 ...

  6. 递归查询SQL语句

    USE [DB] GO /****** Object: View [dbo].[v_menus] Script Date: 02/24/2014 15:55:45 ******/ SET ANSI_N ...

  7. hdoj1010 Temperor of the bone

    Tempter of the Bone Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Othe ...

  8. 开发中tomcat缓存问题

    tomcat-清除缓存 方法一:  conf/server.xml文件  Context path中间加上reloadable="true"  例如:<Context pat ...

  9. 关于django模型里面的__str__和__unicode

    简而言之,就是__str__和__unicode__都是为了再管理站点中加载这个表时想显示什么属性,当然一般都是显示一个name,大体来讲是通用的.下面是抄的csdn上面的一篇文章. str()是Py ...

  10. 创建Ajax对象

    针对不同版本浏览器插件Ajax对象. <script> function createAjax(){ var request=false; //window对象中有XMLHttpReque ...