码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式Java版之一:观察者模式

时间:2015-04-26 16:31:05      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

最近设计模式越来越受到企业和程序员的重视了, 自己作为初学者,将自己学习的点滴贴到博客园,分享一下~

 

java.util包里面提供了对观察者模式的支持,下面是模仿着其中的Observer和Observable写出了我的观察者模式代码。

 

package com.myobserver;

public interface Observer {
    void update(Observable obs, Object obj);
}
package com.myobserver;

public interface Observable {

    public void addObserver(Observer obs);

    public void deleteObserver(Observer obs);

    public void notifyObservers(Object obj);
}

 

package com.myobserver;

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

public class ConcreteObservable implements Observable {

    List<Observer> list = new ArrayList<Observer>();

    @Override
    public void addObserver(Observer obs) {
        // TODO Auto-generated method stub
        list.add(obs);
    }

    @Override
    public void deleteObserver(Observer obs) {
        // TODO Auto-generated method stub
        list.remove(obs);
    }

    @Override
    public void notifyObservers(Object obj) {
        // TODO Auto-generated method stub
        for (Observer observer : list) {
            observer.update(this, obj);
        }
    }

}
package com.myobserver;

public class ConcreteObserver implements Observer {

    @Override
    public void update(Observable obs, Object obj) {
        // TODO Auto-generated method stub
        System.out.println("------------ConcreteObserver received update info"
                + obj + " from" + obs);
    }

}
package com.myobserver;

public class ConcreteObserver2 implements Observer {

    @Override
    public void update(Observable obs, Object obj) {
        // TODO Auto-generated method stub
        System.out.println("------------ConcreteObserver2 received update info"
                + obj + " from" + obs);
    }

}
package com.myobserver;

public class test {

    public static void main(String[] args) {
        ConcreteObservable observable = new ConcreteObservable();
        ConcreteObserver observer1 = new ConcreteObserver();
        ConcreteObserver2 observer2 = new ConcreteObserver2();
        observable.addObserver(observer1);
        observable.addObserver(observer2);
        observable.notifyObservers(" Send a broacast ");
    }
}
输出结果:
------------ConcreteObserver received update info Send a broacast  fromcom.myobserver.ConcreteObservable@d42d08
------------ConcreteObserver2 received update info Send a broacast  fromcom.myobserver.ConcreteObservable@d42d08

 这里主要是为了了解设计模式的思想,所以没有考虑多线程同步。

技术分享

 

设计模式Java版之一:观察者模式

标签:

原文地址:http://www.cnblogs.com/jiangq/p/4457861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!