观察者模式的简单应用

一 观察者模式

定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

二 Java实例

package PostOfficeInstance;

public interface ISubscribe {
	public void registered(Postoffice postoffice);
	public void unregistered(Postoffice postoffice);
	public void getNewspaper();
}

package PostOfficeInstance;

import java.util.ArrayList;

public class Postoffice {
	private ArrayList<ISubscribe>SubscribeList=new ArrayList<ISubscribe>();
	private boolean received;
	public void registeredSubscribe(ISubscribe subscribe) {
		SubscribeList.add(subscribe);
	}
	public void unregisteredSubscribe(ISubscribe subscribe) {
		if(subscribe!=null) SubscribeList.remove(subscribe);
	}
	public void setReceived(boolean received) {
		this.received=received;
	}
	public boolean getReceived() {
		return received;
	}
	
	public void sendNewspaper() {
		if(this.getReceived()==false) return;
		for(ISubscribe subscribe:SubscribeList) {
			subscribe.getNewspaper();
		}
	}
}

package PostOfficeInstance;

public class Subscriber implements ISubscribe{
	private String mName;
	private String mNewspaperName;
	
	public Subscriber(String Name,String NewspaperName) {
		this.mName=Name;
		this.mNewspaperName=NewspaperName;
	}
	public void setName(String name) {
		this.mName=name;
	}
	public final String getName() {
		return mName;
	}
	public void setNewspaperName(String name) {
		this.mNewspaperName=name;
	}
	public final String getNewspaperName() {
		return this.mNewspaperName;
	}
	@Override
	public void registered(Postoffice postoffice) {
		// TODO Auto-generated method stub
		postoffice.registeredSubscribe(this);
	}
	@Override
	public void unregistered(Postoffice postoffice) {
		// TODO Auto-generated method stub
		postoffice.unregisteredSubscribe(this);
	}
	@Override
	public void getNewspaper() {
		// TODO Auto-generated method stub
		System.out.println("I am "+this.mName);
		System.out.println("I received "+this.mNewspaperName);
	}
	
}

package PostOfficeInstance;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Postoffice postoffice=new Postoffice();
		Subscriber 	zhangsan=new Subscriber("zhangsan","Newspaper A");
		Subscriber 	lisi=new Subscriber("lisi","Newspaper B");
		Subscriber 	wangwu=new Subscriber("wangwu","Newspaper c");
		
		postoffice.registeredSubscribe(zhangsan);
		postoffice.registeredSubscribe(lisi);
		postoffice.registeredSubscribe(wangwu);
		
		postoffice.setReceived(true);
		postoffice.sendNewspaper();
	}

}


 

 

三 测试结果

I am zhangsan
I received Newspaper A
I am lisi
I received Newspaper B
I am wangwu
I received Newspaper c


 

 

你可能感兴趣的:(java,String,测试,null,Class,interface)