用java.util.Observable实现Observer模式
本文转载自:dada360778512的博客
原文链接:http://blog.csdn.net/dada360778512/article/details/6977758
Observer模式 主要是观察者与被观察者之间的关系
观察者为羊,被观察者为狼 模仿的场景为狼叫羊跑
代码如下:
1.被观察者类
- package test.pattern.observer;
- import java.util.Observable;
- public class Wolf extends Observable{
- private String name;
- Wolf(String name) {
- this.name = name;
- }
- public void cry(String state){
- System.out.println(this.getName()+ " crying ");
- this.setChanged();
- this.notifyObservers(state);
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
2.观察者类
- package test.pattern.observer;
- import java.util.Observable;
- import java.util.Observer;
- public class Sheep implements Observer {
- private String state = "eating";
- private String name;
- public Sheep(String name){
- this.name = name;
- }
- public void update(Observable o, Object arg) {
- // TODO Auto-generated method stub
- Wolf wolf = (Wolf)o;
- System.out.println(wolf.getName()+" crying and "+arg+" "+this.getName()+" running.....");
- setState("running");
- }
- public String getState() {
- return state;
- }
- public void setState(String state) {
- this.state = state;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
3.测试
- package test.pattern.observer;
- public class TestObserver {
- public static void main(String[] args) {
- Wolf wolf = new Wolf("wolf1");
- Sheep sheep1 = new Sheep("sheep1");
- Sheep sheep2 = new Sheep("sheep2");
- Sheep sheep3 = new Sheep("sheep3");
- //注册观察者,sheep1,sheep2加入,sheep3未加入
- wolf.addObserver(sheep1);
- wolf.addObserver(sheep2);
- String wolfStat = "hungry";
- //wolf begin cry
- wolf.cry(wolfStat);
- }
- }
4.结果:
wolf1 crying
wolf1 crying and hungry sheep2 running.....
wolf1 crying and hungry sheep1 running.....
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。