1、创建被观察者:
package org.jason.Observer; import java.util.Observable; //被观察者 public class Writer extends Observable { private String authorName; private Article article; public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public Article getArticle() { return article; } public void setArticle(Article article) { this.article = article; } public void publish() { //设置状态变化 this.setChanged(); System.out.println("作者:"+this.getAuthorName()+" 发布新文章啦"); System.out.println("--标题:"+this.getArticle().getTitile()); System.out.println("--内容:"+this.getArticle().getContent()); //通知所有观察者 this.notifyObservers(); } }
package org.jason.Observer; public class Article { private String titile; private String content; public String getTitile() { return titile; } public void setTitile(String titile) { this.titile = titile; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
2、创建观察者:
package org.jason.Observer; import java.util.Observable; import java.util.Observer; //观察者 public class Reader implements Observer{ private String readerName; public String getReaderName() { return readerName; } public void setReaderName(String readerName) { this.readerName = readerName; } @Override public void update(Observable o, Object arg) { Writer w=(Writer)o; Article a=w.getArticle(); System.out.println("读者:"+this.getReaderName()); System.out.println("订阅到如下文章:"); System.out.println("标题:"+a.getTitile()); System.out.println("内容:"+a.getContent()); } }
3、测试程序:
package org.jason.Observer; public class TestMain { public static void main(String args[]) { Article article=new Article(); article.setTitile("设计模式-观察者模式应用"); article.setContent("..............................."); Writer w =new Writer(); w.setAuthorName("石头城程序猿"); Reader r1=new Reader(); r1.setReaderName("张三"); Reader r2=new Reader(); r2.setReaderName("李四"); w.addObserver(r1); w.addObserver(r2); w.setArticle(article); w.publish(); } }
4、输出结果:
作者:石头城程序猿 发布新文章啦
--标题:设计模式-观察者模式应用
--内容:...............................
读者:李四
订阅到如下文章:
标题:设计模式-观察者模式应用
内容:...............................
读者:张三
订阅到如下文章:
标题:设计模式-观察者模式应用
内容:...............................