设计模式(Design Pattern) - 行为型模式(Behavioral Pattern) - 观察者模式(Observer)
1、当一个对象(被观察)变化时,其它关联对象(观察者)都会随着变化!
2、关联关系:一对多;(一是被观察对象,多是观察者)
一、说明:
1、Observer 观察者(接口);
2、Guardian 观察者.实现类;
3、Watched 被观察(接口);
4、AbstractWatched 被观察对象(抽象类);
5、Baby 被观察对象.实现类。
二、Java实现,代码如下:
1、Observer
package com.designPattern.observer;
/**
* 观察者
*
*/
public interface Observer {
/**
* 观察者 - 操作
*/
public void action();
}
2、Guardian
package com.designPatterns.observer;
/**
* 观察者 - 实现类
*
*/
public class Guardian implements Observer {
private String name;
public Guardian(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void action() {
System.out.println(name + " : I'm coming !");
}
}
3、Watched
package com.designPattern.observer;
/**
* 被观察 - 接口
*
*/
public interface Watched {
/**
* 添加观察者
* @param entity 观察者
*/
public void addObserver(Observer entity);
/**删除观察者
* @param entity 观察者
*/
public void delObserver(Observer entity);
/**
* 通知观察者
*/
public void notifyObserver();
/**
* 被观察对象的操作
*/
public void operate();
}
4、AbstractWatched
package com.designPattern.observer;
import java.util.ArrayList;
import java.util.List;
/**
* 被观察 - 抽象类
*
*/
public abstract class AbstractWatched implements Watched {
// 观察者列表
List<Observer> list = new ArrayList<>();
@Override
public void addObserver(Observer entity) {
list.add(entity);
}
@Override
public void delObserver(Observer entity) {
list.remove(entity);
}
@Override
public void notifyObserver() {
for (Observer entity : list) {
entity.action();
}
}
}
5、Baby
package com.designPatterns.observer;
/**
* 被观察 - 实现类
*
*/
public class Baby extends AbstractWatched {
private String name;
public Baby(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void operate() {
System.out.println(name + " : Cry!");
notifyObserver();
}
}
6、Test
package com.designPattern.observer;
/**
* 测试类
*
*/
public class Test {
public static void main(String[] args) {
Baby baby = new Baby("baby");
Guardian father = new Guardian("father");
Guardian mother = new Guardian("mother");
Guardian grandfather = new Guardian("grandfather");
Guardian grandmother = new Guardian("grandmother");
baby.addObserver(father);
baby.addObserver(mother);
baby.addObserver(grandfather);
baby.addObserver(grandmother);
baby.operate();
}
}
7、输出:
baby : Cry!
father : I’m coming !
mother : I’m coming !
grandfather : I’m coming !
grandmother : I’m coming !