Observer Pattern 观察者模式

import java.util.Observable;
import java.util.Observer;

/**
 * 
 * @author King
 * 本例中:被观察者为偷钱包的贼,观察者为抓贼的警察
 * 贼一旦发生偷钱包行为,就会被警察抓住
 *
 */
public class ObservePattern {
    
    public static void main(String args[]){
        Thief thief1 = new Thief();
        Police police1 = new Police();
        
        //被观察者被监视
        thief1.addObserver(police1); 
        thief1.stealPurse();
    }

}

/*
 * 被观察的对象继承Ovsevable
 * 
 */
class Thief extends Observable{
    
    //被观察者的行为动作
    public void stealPurse(){
        System.out.println("stealing purse");  
        
        //被观察者的状态发生改变,并通知观察者
        super.setChanged();
        super.notifyObservers();
    }
    
}


/*
 * 观察者实现Observer接口
 * 
 */
class Police implements Observer{

    //针对被观察者的行为,观察者采取的行为
    @Override
    public void update(Observable arg0, Object arg1) {
        // TODO Auto-generated method stub
        System.out.println("catch the thief");
    }
    
}

猜你喜欢

转载自kingbinchow.iteye.com/blog/1733421