Home | History | Annotate | Download | only in quicksearchbox
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.quicksearchbox;
     18 
     19 import android.database.DataSetObservable;
     20 import android.database.DataSetObserver;
     21 
     22 import java.util.Collections;
     23 import java.util.List;
     24 
     25 /**
     26  * Abstract base class for corpus rankers.
     27  */
     28 public abstract class AbstractCorpusRanker implements CorpusRanker {
     29 
     30     private final DataSetObservable mDataSetObservable = new DataSetObservable();
     31 
     32     private final Corpora mCorpora;
     33 
     34     // Cached list of ranked corpora. Set to null when mCorpora changes.
     35     private List<Corpus> mRankedCorpora;
     36 
     37     public AbstractCorpusRanker(Corpora corpora) {
     38         mCorpora = corpora;
     39         mCorpora.registerDataSetObserver(new CorporaObserver());
     40     }
     41 
     42     /**
     43      * Creates a ranked list of corpora.
     44      */
     45     protected abstract List<Corpus> rankCorpora(Corpora corpora);
     46 
     47     public List<Corpus> getRankedCorpora() {
     48         if (mRankedCorpora == null) {
     49             mRankedCorpora = Collections.unmodifiableList(rankCorpora(mCorpora));
     50         }
     51         return mRankedCorpora;
     52     }
     53 
     54     public void registerDataSetObserver(DataSetObserver observer) {
     55         mDataSetObservable.registerObserver(observer);
     56     }
     57 
     58     public void unregisterDataSetObserver(DataSetObserver observer) {
     59         mDataSetObservable.unregisterObserver(observer);
     60     }
     61 
     62     protected void notifyDataSetChanged() {
     63         mDataSetObservable.notifyChanged();
     64     }
     65 
     66     private class CorporaObserver extends DataSetObserver {
     67         @Override
     68         public void onChanged() {
     69             mRankedCorpora = null;
     70             notifyDataSetChanged();
     71         }
     72     }
     73 }
     74