当前位置:首页 > 开发 > 编程语言 > JDK JVM > 正文

JDK观察者模式实现Observer Observable

发表于: 2013-02-05   作者:antlove   来源:转载   浏览:
摘要: JDK提供了观察者模式的实现类java.util.Observer,java.util.Observable. java.util.Observer为观察者。 java.util.Observable观察物。 1.观察物 package observer; import java.util.Observable; public class Publisher extends
JDK提供了观察者模式的实现类java.util.Observer,java.util.Observable.
java.util.Observer为观察者。
java.util.Observable观察物。

1.观察物
package observer;
import java.util.Observable;
public class Publisher extends Observable {
	private String magazineName;
	public String getMagazineName() {
		return magazineName;
	}
	public void publish(String magazineName) {
		this.magazineName = magazineName;
		setChanged();// set the changed signal
		notifyObservers();// notify all the observers
	}
}

2.观察者
package observer;
import java.util.Observable;
import java.util.Observer;
public class Reader implements Observer {
	// when the observable changed , 
	// it will notify all the observers and this method will be invoke
	@Override
	public void update(Observable o, Object arg) {
		if(o instanceof Publisher){
			Publisher p = (Publisher) o;
			System.out.println("i want to read magazine. " + p.getMagazineName());
		}
	}
}

3.测试类
package observer;
public class Main {
	public static void main(String[] args) {
		// create observer
		Reader reader=new Reader();
		// create observable
		Publisher publisher = new Publisher();
		// add observer
		publisher.addObserver(reader);
		// observable do some action
		publisher.publish("I am antlove.");
	}
}

JDK观察者模式实现Observer Observable

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号