观察者设计模式(Obsever Design Pattern)案列
package xyz. pattern. observer. subpackage2;
public interface Obsever {
public void toUpdate ( ) ;
}
package xyz. pattern. observer. subpackage2;
public class ConcreteObseverA implements Obsever {
private Subject s;
public ConcreteObseverA ( Subject s) {
this . s= s;
}
public void attachToSubject ( ) {
if ( s!= null) {
s. addObsever ( this ) ;
}
}
public void detachToSubject ( ) {
if ( s!= null) {
s. removeObsever ( this ) ;
}
}
@Override
public void toUpdate ( ) {
int state = s. getState ( ) ;
switch ( state) {
case 0 :
actionA ( state) ;
break ;
case 1 :
actionB ( state) ;
break ;
default :
defaultAction ( state) ;
break ;
}
}
private void actionA ( int state) {
System. out. println ( "状态" + state+ ":" + this . getClass ( ) . getSimpleName ( ) + "采取行动A" ) ;
}
private void actionB ( int state) {
System. out. println ( "状态" + state+ ":" + this . getClass ( ) . getSimpleName ( ) + "采取行动A" ) ;
}
private void defaultAction ( int state) {
System. out. println ( "状态" + state+ ":" + this . getClass ( ) . getSimpleName ( ) + "采取行动A" ) ;
}
}
package xyz. pattern. observer. subpackage2;
public class ConcreteObseverB implements Obsever {
private Subject s;
public ConcreteObseverB ( Subject s) {
this . s= s;
}
public void attachToSubject ( ) {
if ( s!= null) {
s. addObsever ( this ) ;
}
}
public void detachToSubject ( ) {
if ( s!= null) {
s. removeObsever ( this ) ;
}
}
@Override
public void toUpdate ( ) {
int state = s. getState ( ) ;
switch ( state) {
case 0 :
actionA ( state) ;
break ;
case 1 :
actionB ( state) ;
break ;
default :
defaultAction ( state) ;
break ;
}
}
private void actionA ( int state) {
System. out. println ( "状态" + state+ ":" + this . getClass ( ) . getSimpleName ( ) + "采取行动A" ) ;
}
private void actionB ( int state) {
System. out. println ( "状态" + state+ ":" + this . getClass ( ) . getSimpleName ( ) + "采取行动A" ) ;
}
private void defaultAction ( int state) {
System. out. println ( "状态" + state+ ":" + this . getClass ( ) . getSimpleName ( ) + "采取行动A" ) ;
}
}
package xyz. pattern. observer. subpackage2;
import java. util. AbstractList;
import java. util. ArrayList;
public class Subject {
private AbstractList< Obsever> obsevers= new ArrayList < > ( ) ;
private int state;
public int getState ( ) {
return state;
}
public void setState ( int state) {
this . state= state;
notofyAllObsevers ( ) ;
}
private void notofyAllObsevers ( ) {
for ( Obsever o: obsevers) {
o. toUpdate ( ) ;
}
}
public void addObsever ( Obsever o) {
obsevers. add ( o) ;
}
public void removeObsever ( Obsever o) {
obsevers. remove ( o) ;
}
}
package xyz. pattern. observer. subpackage2;
public class Client {
public static void main ( String[ ] args) {
Subject s = new Subject ( ) ;
ConcreteObseverA obseverA = new ConcreteObseverA ( s) ;
obseverA. attachToSubject ( ) ;
ConcreteObseverB obseverB = new ConcreteObseverB ( s) ;
obseverB. attachToSubject ( ) ;
s. setState ( 0 ) ;
s. setState ( 1 ) ;
s. setState ( - 1 ) ;
}
}