package com.maom.design.D_10_Observer;
import java.util.Observable;
import java.util.Observer;
/**
* @Title: D_10_Observer
* @Description: 10_观察者模式
* @Author maohb
* @Version 1.0
*/
public class D_10_Observer {
public static void main(String[] args) {
BlogUser user = new BlogUser();
// 加载观察者
user.addObserver(new MyObServer());
// 测试
user.publishBlog("哈哈,博客上线了", "大家多来访问");
}
}
class BlogUser extends Observable {
/** 被观察方法 */
public void publishBlog(String articleTitle,String articleContent) {
Article art = new Article();
art.setArticleTitle(articleTitle);
art.setArticleContent(articleContent);
System.out.println("博主:发表新文章,文章标题:" + articleTitle + ",文章内容:" + articleContent);
// 通知观察者
this.setChanged();
this.notifyObservers(art);
}
}
class Article {
private String articleTitle;
private String articleContent;
public String getArticleTitle() {
return articleTitle;
}
public void setArticleTitle(String articleTitle) {
this.articleTitle = articleTitle;
}
public String getArticleContent() {
return articleContent;
}
public void setArticleContent(String articleContent) {
this.articleContent = articleContent;
}
}
class MyObServer implements Observer {
public void update(Observable o, Object arg) {
Article art = (Article)arg;
// 观察者行为
System.out.println("博主发表了新的文章,快去看吧!");
System.out.println("博客标题为:" + art.getArticleTitle());
System.out.println("博客内容为:" + art.getArticleContent());
}
}
设计模式笔记_10_观察者模式
最新推荐文章于 2024-09-08 21:56:57 发布