当一个对象变化时,其它依赖该对象的对象都会收到通知,并且随着变化!对象之间是一种一对多的关系
package study.org;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
Subject subject = new ConcreteSubject();
Observer concreteObserver1 = new ConcreteObserver1();
Observer concreteObserver2 = new ConcreteObserver2();
subject.add(concreteObserver1);
subject.add(concreteObserver2);
subject.notifyObserver();
}
}
abstract class Observer {
abstract void response();
}
class ConcreteObserver1 extends Observer{
@Override
void response() {
System.out.println("ConcreteObserver1 response method");
}
}
class ConcreteObserver2 extends Observer{
@Override
void response() {
System.out.println("ConcreteObserver2 response method");
}
}
abstract class Subject {
protected List<Observer> list = new ArrayList<Observer>();
public void add(Observer observer) {
list.add(observer);
}
public void remove(Observer observer) {
list.remove(observer);
}
public abstract void notifyObserver();
}
class ConcreteSubject extends Subject {
@Override
public void notifyObserver() {
for (Observer observer : list) {
observer.response();
}
}
}
网友评论