1. 程式人生 > >觀察者模式的架構

觀察者模式的架構

notify 請求 == super ner urn ins tin override

Bean Manager View

manager負責網絡請求,繼承 java.util.Observable

主要內容:

public class RequestManger extends Observable {
    private static ConsultListManger mManager;


    private String TAG = this.getClass().getSimpleName();

    private ConsultListManger() {
    }

    public synchronized static ConsultListManger getInstance() {
        if (mManager == null) {
            mManager = new RequestManger ();
        }
        return mManager;
    }

   //網絡請求的方法 public void request() {
    //在網絡請求出現結果後調用    
    setChanged();
    notifyObservers(informationListBean);

    如:
    request.setHttpListener(new HttpListener<String>() {
                @Override
                public void onSuccess(String s, Response<String> response) {
                    super.onSuccess(s, response);
                        setChanged();
                        notifyObservers(informationListBean);
                    } 
                }

                @Override
                public void onFailure(HttpException e, Response<String> response) {
                    super.onFailure(e, response);
                    setChanged();
                    notifyObservers("網絡請求失敗!");
                }
            });

  

  } }

  

View是activity或者fragment,需要實現 java.util.Observer,實現Observer的update()方法。

主要內容:

public class Fragment extends Fragment implements Observer{

    
    ........
@Override public void update(Observable o, Object arg) {   if (o instanceof RequestManager) {      if (arg instanceof Bean) {      setData(((Bean) arg));    }     }    }

    private void setData(Bean bean){
      //設置UI
    }
}                

  

觀察者模式的架構