观察者模式
观察者接口
public interface Observer {
public void receiveMessage ( String message) ;
}
观察者接口实现类
public class ObserverImpl implements Observer {
private String name;
public ObserverImpl ( String name) {
super ( ) ;
this . name = name;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
@Override
public void receiveMessage ( String message) {
System. out. println ( name+ "收到消息" + message) ;
}
}
给观察者发信息的接口(抽象主题)
public interface Subject {
public void addObserver ( Observer observer) ;
public void deleteObserver ( Observer
observer) ;
public void sentMessage ( String message) ;
}
抽象主题的实现类
public class SubjectImpl implements Subject {
private ArrayList< Observer> arrayList= new ArrayList < > ( ) ;
public SubjectImpl ( ) {
super ( ) ;
}
@Override
public void addObserver ( Observer observer) {
if ( observer!= null) {
arrayList. add ( observer) ;
}
}
@Override
public void deleteObserver ( Observer observer) {
if ( arrayList!= null) {
if ( observer!= null) {
arrayList. remove ( observer) ;
}
}
}
@Override
public void sentMessage ( String message) {
Iterator< Observer> iterator = arrayList. iterator ( ) ;
while ( iterator. hasNext ( ) ) {
Observer observer = iterator. next ( ) ;
observer. receiveMessage ( message) ;
}
}
}
测试
public class Test01 {
public static void main ( String[ ] args) {
ObserverImpl observer1 = new
ObserverImpl ( "lbc" ) ;
ObserverImpl observer2 = new
ObserverImpl ( "hlq" ) ;
ObserverImpl observer3 = new
ObserverImpl ( "lhj" ) ;
SubjectImpl subject = new SubjectImpl ( ) ;
subject. addObserver ( observer1) ;
subject. addObserver ( observer2) ;
subject. addObserver ( observer3) ;
subject. sentMessage ( "更新了消息" ) ;
}
}