Observer -- 观察者模式

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();
	}

}



















发布了224 篇原创文章 · 获赞 209 · 访问量 72万+
展开阅读全文

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

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

分享到微信朋友圈

×

扫一扫,手机浏览