设计模式——观察者模式

来源:互联网 发布:php模拟登录get 编辑:程序博客网 时间:2024/06/14 14:46

         将观察者和被观察的对象划分开,创建一个容易存放被观察的对象,当观察者观察时,只需要调容器中的内容就可以;当某个Class不需要被观察时,直接在容器中将其删除即可。

         废话不多,直接上小例子,几分钟敲完一切明了。


//订阅者public interface ISubScribe {//有新的报纸就会通知void hasNewPaper();}

public interface INewsPaper {//添加订阅者void RegisterSubscriber(ISubScribe f_subScribe);//取消订阅void removeSubScriber(ISubScribe f_subScribe);//发送报纸void SendPaper();}
public class SubHuman implements ISubScribe{//订阅者的名字private String p_name;public SubHuman(String f_name){this.p_name = f_name;}@Overridepublic void hasNewPaper() {// TODO 有新报纸了System.out.println(p_name + "!!有新报纸了,请查收!");}}
public class PeopleNewsPaper implements INewsPaper{//容器private List<ISubScribe> subList = new ArrayList<ISubScribe>();@Overridepublic void RegisterSubscriber(ISubScribe f_subScribe) {// TODO Auto-generated method stubsubList.add(f_subScribe);}@Overridepublic void SendPaper() {// TODO Auto-generated method stubfor(ISubScribe _sub : subList){_sub.hasNewPaper();}}@Overridepublic void removeSubScriber(ISubScribe f_subScribe) {// TODO Auto-generated method stubif(subList.indexOf(f_subScribe) >=0){subList.remove(f_subScribe);}}}
public class Test {public static void main(String[] args){PeopleNewsPaper pnp = new PeopleNewsPaper();SubHuman sh1 = new SubHuman("张无忌");SubHuman sh2 = new SubHuman("周芷若");//两个人都订报纸了pnp.RegisterSubscriber(sh1);pnp.RegisterSubscriber(sh2);//发报纸pnp.SendPaper();System.out.println("报纸发完了~");//其中一个人退订pnp.removeSubScriber(sh2);pnp.SendPaper();System.out.println("报纸又发完了~");}}


0 0
原创粉丝点击