Observer -- 观察者模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 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();
	}

}



















展开阅读全文

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