标签:util ack 一个 mail nbsp 技术分享 ace test set
观察者模式定义了对象之间的一对多依赖,这样依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新
原则
/**
* Created by xjw on 2017/11/9 16:53
* Email 1521975316@qq.com
*/
public class Test {
public interface Display {
void display();
}
public interface Observer {
void update(int a, int b, int c);
}
public interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifiObserver();
}
static class WeekDate implements Subject {
private List<Observer> observers;
private int a;
private int b;
private int c;
public WeekDate() {
this.observers = new ArrayList<>();
}
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
int i = observers.indexOf(observer);
if (i >= 0) {
observers.remove(i);
}
}
@Override
public void notifiObserver() {
for (int i = 0; i < observers.size(); i++) {
observers.get(i).update(a, b, c);
}
}
public void setData(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
notifiObserver();
}
}
static class AObserver implements Observer, Display {
private int a;
private int b;
private int c;
public AObserver(Subject subject) {
subject.addObserver(this);
}
@Override
public void update(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
display();
}
@Override
public void display() {
System.out.println("a:" + a + ";b:" + b + ";c:" + c);
}
}
public static void main(String[] args) {
WeekDate subject = new WeekDate();
AObserver observer = new AObserver(subject);
subject.setData(1, 2, 3);
subject.setData(4, 5, 6);
subject.removeObserver(observer);
subject.setData(7, 8, 9);
}
}
java.util.Observer
)java.util.Observable
),相当于主题Subjectjava学习群669823128
标签:util ack 一个 mail nbsp 技术分享 ace test set
原文地址:http://www.cnblogs.com/-reset/p/7810820.html