Chinaunix首页 | 论坛 | 博客
  • 博客访问: 383054
  • 博文数量: 85
  • 博客积分: 1504
  • 博客等级: 上尉
  • 技术积分: 928
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-04 12:20
文章分类

全部博文(85)

文章存档

2011年(66)

2010年(19)

分类: Java

2011-06-01 21:17:17

package com.bbsoft.observer.javaUtil.test;
import java.util.Observable;
/**
*
* @author bbsoft
*
*/
public class PostOffice extends Observable {
    private String magazineName;
    private String publishDate;
    /**
     *
     * @param magazineName
     *            - magazine Name
     * @param publishDate
     *            - publish Date
     */
    public void publishMagazine(String magazineName, String publishDate) {
        this.magazineName = magazineName;
        this.publishDate = publishDate;
        notifySubsribers();
    }
    private void notifySubsribers() {
        String[] args = new String[2];
        args[0] = magazineName;
        args[1] = publishDate;
        this.setChanged();
        this.notifyObservers(args);

    }

}

package com.bbsoft.observer.javaUtil.test;

import java.util.Observable;
import java.util.Observer;

public class Subscriber implements Observer {

    private Observable observer;

    private String subscriberName;
    private String magazineName;
    private String publishDate;

    Subscriber(Observable observer, String subscriberName) {
        this.observer = observer;
        this.subscriberName = subscriberName;
        this.observer.addObserver(this);
    }

    public void update(Observable o, Object arg) {
        if (o instanceof PostOffice) {

            String[] publishInfo = (String[]) arg;

            magazineName = publishInfo[0];
            publishDate = publishInfo[1];

            display();
        }

    }

    public void display() {
        System.out.println("subscriber Name: " + subscriberName);
        System.out.println("magazine Name: " + magazineName);
        System.out.println("publish Date: " + publishDate);
        System.out.println("------------------------------");
    }

}

测试类:

package com.bbsoft.observer.javaUtil.test;

public class TestJavaUtilObserver {
    public static void main(String[] args) {

        PostOffice post = new PostOffice();

        Subscriber tim = new Subscriber(post, "tim");
        Subscriber mike = new Subscriber(post, "mike");

        post.publishMagazine("advanced", "2009-6-30");

        post.deleteObserver(mike);

        post.publishMagazine("haha", "2009-6-30");
    }
}

阅读(1431) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~