`
DavyJones2010
  • 浏览: 151824 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

DesignPattern : Observer

阅读更多

1. Introduction

    1. We can infer Observer Design Pattern from JDK GUI part.

    2. The AWT and Swing GUI components are using Observer Design Pattern which we will discuss later.

 

2. A simple example for showing the effect of using Observer Design Pattern

package edu.xmu.designPattern.DesignPattern_Observer;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonTest
{
	public static void main(String[] args)
	{
		Frame frame = new Frame("Button Test");

		Button button = new Button("Press Me");

		button.addActionListener(new ButtonHandler());
		button.addActionListener(new ButtonHandler2());

		frame.add(button, BorderLayout.CENTER);

		frame.pack();
		frame.setVisible(true);
	}
}

class ButtonHandler implements ActionListener
{

	public void actionPerformed(ActionEvent e)
	{
		String label = e.getActionCommand();
		System.out.println(label);
	}

}

class ButtonHandler2 implements ActionListener
{

	public void actionPerformed(ActionEvent e)
	{
		String label = e.getActionCommand() + "2";
		System.out.println(label);
	}

}

    Comments:

        1) Function of this app is that every time we click the button, the console will print the label of the button.

        2) Pay attention to the button.addActionListener(new ButtonHandler());

            This means every time we click the button, the method called actionPerformed in ButtonHandler() will be executed automatically.

             How did JDK achieve this? Why this method will be executed AUTOMATICALLY?

        3) Observer Design Pattern Lays behind.

 

3. Observer Design Pattern

    1) Observer Design Pattern defines a relationship of One To Many.

        Several listeners observe the state of the target at the same time.

        Whenever the state of the target changed, all the listeners will get informed.

    2) The target in the example above can be seen as the button.

        The listeners in the example above can be seen as the instance of ButtonHandler and ButtonHandlers.

    3) Roles in Observer Design Pattern

        1) Abstract Subject:

                1. Includes a collection which contains all the reference to its Observer.

                2. Every Abstract Subject can have serveral listeners/observers.

                3. Abstract Subject exposes interfaces which can add and remove Listeners/Observers.

        2) Abstract Observer:

                1. An interface for all the Observer so that they can get informed every time the state of its subject changed.

        3) Concrete Subject:

                1. Every time its state changed, it should inform all the observer that stored in its observer collection.

        4) Concrete Observer:

                1. To perform the real action every time they get informed.

     4) Class diagram is as below


4. A simple example for explaining Observer Design Pattern

    1) AbstractSubject

package edu.xmu.designPattern.DesignPattern_Observer;

public interface AbstractSubject
{
	public void addListener(AbstractObserver abstractObserver);

	public void removeListener(AbstractObserver abstractObserver);

	public void notifyListeners(String info);
}

    2) AbstractObserver

package edu.xmu.designPattern.DesignPattern_Observer;

public interface AbstractObserver
{
	public void actionPerformed(String info);
}

    3) ConcreteSubject --> Regard this as the Button in previous example

package edu.xmu.designPattern.DesignPattern_Observer;

import java.util.ArrayList;
import java.util.List;

public class ConcreteSubject implements AbstractSubject
{
	private List<AbstractObserver> observerList = new ArrayList<AbstractObserver>();

	public void addListener(AbstractObserver observer)
	{
		observerList.add(observer);
	}

	public void removeListener(AbstractObserver observer)
	{
		observerList.remove(observer);
	}

	public void notifyListeners(String info)
	{
		for (AbstractObserver observer : observerList)
		{
			observer.actionPerformed(info);
		}
	}

}

    4) ConcreteObserverOne --> Regard this as ButtonHander in previous example

package edu.xmu.designPattern.DesignPattern_Observer;

public class ConcreteObserverOne implements AbstractObserver
{

	public void actionPerformed(String info)
	{
		System.out.println("ConcreteObserverOne ---> " + info);
	}

}

    5) ConcreteObserverTwo --> Regard this as ButtonHandler2 in previous example

package edu.xmu.designPattern.DesignPattern_Observer;

public class ConcreteObserverTwo implements AbstractObserver
{

	public void actionPerformed(String info)
	{
		System.out.println("ConcreteObserverTwo ---> " + info);
	}

}

    6) Test Case

package edu.xmu.designPattern.DesignPattern_Observer;

import org.junit.Test;

public class ObserverTest
{
	@Test
	public void test()
	{
		AbstractSubject subject = new ConcreteSubject();

		AbstractObserver observerOne = new ConcreteObserverOne();
		AbstractObserver observerTwo = new ConcreteObserverTwo();

		subject.addListener(observerOne);
		subject.addListener(observerOne);
		subject.addListener(observerTwo);

		subject.notifyListeners("Hello world!");
	}
}

    7) Output

ConcreteObserverOne ---> Hello world!
ConcreteObserverOne ---> Hello world!
ConcreteObserverTwo ---> Hello world!

    Comments:

        1) Pay attention to Line 16 in ObserverTest.java, we add one instance of observer two times to a subject.

            This instance of observer will be added two times and called two times every time the state of the subject changed.

            Because the subject keep a List to store its listeners/observers. If it keep a Set(HashSet), then oberverOne will not be added two times.

            Please pay attention to the diffence of List and Set!!!

        2) And in Swing or AWT implementation of JDK, the underlying of all kinds of listeners are stored in ArrayList and not HashSet

 

 Reference Links:

    1) http://en.wikipedia.org/wiki/Observer_pattern 

  • 大小: 48.8 KB
分享到:
评论

相关推荐

    DesignPattern::pencil:设计模式_java实现以及详解

    本资源“DesignPattern::pencil:设计模式_java实现以及详解”提供了一套详细的学习材料,帮助开发者理解和应用设计模式。 该资源的作者是“养码青年-Style”,他通过这个项目记录了自己的设计模式学习过程。鼓励...

    Observer HeadFirst design pattern

    在"Observer HeadFirst design pattern"中,作者通过生动的比喻和互动式的例子,帮助读者深入理解观察者模式的核心概念和实现方式。 观察者模式的核心思想是将"主题"(Subject)与"观察者"(Observer)解耦,主题...

    DesignPattern:C#设计模式示例

    "DesignPattern:C#设计模式示例"这个资源很可能是包含多个C#实现的设计模式示例代码库。 设计模式通常分为三类:创建型、结构型和行为型。每种模式都解决了特定场景下的问题,并提供了良好的代码组织和扩展性。 ...

    FOAD-DesignPattern:FOAD-DesignPattern

    3. 观察者模式(Observer Pattern): 观察者模式定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。在C#中,可以通过实现`System.ComponentModel....

    com.designpattern.state_observer.rar

    在给定的“com.designpattern.state_observer.rar”压缩包中,我们可以期待找到有关“状态模式(State Pattern)”和“观察者模式(Observer Pattern)”的示例代码或教程。这两种模式都是行为设计模式,它们在处理...

    design pattern

    它们分别是:单例模式(Singleton)、策略模式(StrategyPattern)、适配器模式(AdapterPattern)、装饰者模式(DecoratorPattern)、抽象工厂模式(AbstractFactoryPattern)、观察者模式(ObserverPattern)、...

    DesignPattern:设计模式小Demo

    设计模式是软件工程中的一种最佳实践,用于解决在软件设计中常见的...以上就是这个DesignPattern小Demo中可能会涵盖的设计模式,通过这些模式的实例,你可以更好地理解和应用它们到实际项目中,提升你的Java编程能力。

    designPattern:练习设计模式

    本项目"designPattern:练习设计模式"提供了一个学习和实践各种设计模式的平台。 1. **单例模式**:确保一个类只有一个实例,并提供一个全局访问点。在Java中,单例模式通常通过双重检查锁定、静态内部类或枚举来...

    DesignPattern:这是针对不同设计人员的测试项目

    这个名为"DesignPattern:这是针对不同设计人员的测试项目"的压缩包,显然是一个与设计模式相关的学习或测试资源,特别关注的是Java语言的应用。Scott可能是该项目的创建者或者主要贡献者,而“调整”可能指的是对...

    DesignPattern:来自 http 的设计模式参考

    在"DesignPattern-master"这个压缩包中,可能包含了这些模式的Java实现示例,以及相关的解释和用法说明。通过学习和应用这些模式,开发者可以提高代码质量,降低维护成本,并提升软件系统的可扩展性。对于任何Java...

    DesignPattern:有关设计模式的一些演示

    这个名为"DesignPattern:有关设计模式的一些演示"的项目,可能是为了帮助开发者理解和应用各种设计模式。 设计模式分为三大类:创建型、结构型和行为型。创建型模式关注对象的创建过程,如单例(Singleton)、工厂...

    designpattern:Head First 设计模式练习

    再者,观察者模式(Observer)定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。在Java中,`java.util.Observable`和`java.util.Observer`接口可以用来实现这个...

    DesignPattern:设计模式.net源代码

    本资源"DesignPattern:设计模式.net源代码"提供了一套基于.NET实现的设计模式示例,旨在帮助程序员更好地理解和应用这些模式。 在"DesignPattern-master"这个压缩包中,你可能找到的文件结构和内容包括: 1. **...

    DesignPattern:设计模式

    DesignPattern-master这个压缩包可能包含了一个关于设计模式的项目或者教程资源。 设计模式分为三类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)和行为型模式(Behavioral Patterns)...

    designPattern:设计模式相关代码实现

    "designPattern:设计模式相关代码实现"这个项目,显然提供了不同设计模式在Java语言中的实际应用示例。 在Java世界里,设计模式主要分为三大类:创建型模式、结构型模式和行为型模式。每种模式都针对特定的编程问题...

    Swift DesignPattern

    本资料"Swift DesignPattern"包含了一些Swift语言中的常见设计模式实例,下面我们将详细探讨这些设计模式及其在Swift中的应用。 1. **单例模式(Singleton)**:单例模式确保一个类只有一个实例,并提供全局访问点...

    DesignPattern:设计模式演示程序

    这个名为"DesignPattern"的压缩包文件很可能包含了一个Java实现的各种设计模式的示例程序。 在这个"DesignPattern-master"目录中,我们可以期待找到一系列与设计模式相关的Java源代码文件(.java),每个文件或...

    designPattern:코딩사전님의정정정리

    "designPattern:코딩사전님의정정정리"可能是某位名为"정정전"的专家或教师对设计模式进行整理和修正后的资料集合,旨在帮助开发者更好地理解和应用这些模式。 首先,设计模式分为三大类:创建型、结构型和行为型...

    Design Pattern英文版

    设计模式(Design Pattern)是软件工程中的一种经验总结,它是在特定上下文中为解决常见问题而提出的一套可复用的解决方案。设计模式并不直接实现为代码,而是提供了一种在面向对象设计中如何处理常见问题的指南。...

    DesignPattern:经验丰富的面向对象软件开发人员使用的最佳实践

    "DesignPattern:经验丰富的面向对象软件开发人员使用的最佳实践"这个主题旨在探讨这些经过时间验证的策略。 设计模式并不具体到某一编程语言,但Java作为一款广泛应用的面向对象语言,它的特性使得设计模式得以高效...

Global site tag (gtag.js) - Google Analytics