原创

Observer -- 观察者模式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://xxlcube.blog.csdn.net/article/details/8230852
package observer;

public interface Subject {

	void attach(Observer observer);
	
	void detach(Observer observer);
	
	void inform();
	
}


package observer;

public interface Observer {

	void update(Object o);
	
}

package observer;

import java.util.Vector;

public class SubjectImpl implements Subject {

	Vector<Observer> observers = new Vector<Observer>();
	
	@Override
	public void attach(Observer observer) {
		// TODO Auto-generated method stub
		observers.addElement(observer);
	}

	@Override
	public void detach(Observer observer) {
		// TODO Auto-generated method stub
		observers.removeElement(observer);
	}

	@Override
	public void inform() {
		// TODO Auto-generated method stub
		Object o = new Object();
		for(Observer ob:observers) {
			ob.update(o);
		}
	}

}

package observer;

public class ObserverImpl implements Observer {

	@Override
	public void update(Object o) {
		// TODO Auto-generated method stub
		System.out.println("Observer reveives Information !");
	}

}


package observer;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SubjectImpl si = new SubjectImpl();
		si.attach(new ObserverImpl());
		si.inform();
	}

}



















文章最后发布于: 2012-11-27 16:57:13
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 酷酷鲨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览