首页 > 代码库 > android里的观察者模式

android里的观察者模式

状况:遇到android程序中后入栈的一个Activity需要更新之前一个或者两个以上Activity中的数据时使用

[1].[代码] [Java]代码 跳至 [1]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* 观察者 */
publicinterface Observer {
    voidupdate(Object... objs);
}
/* 被观察者 使用一个抽象类方便扩展 */
publicabstract class Observable<T> {
     
     
    publicfinal transient ArrayList<HashMap<String, T>> obserList = newArrayList<HashMap<String,T>>();
     
    /* 添加观察者 包括名称及本生 */
    publicvoid attachObserver(String obName, T ob) {
        if(obName == null|| ob == null)thrownew NullPointerException();
        synchronized(obserList) {
            HashMap<String, T> map = newHashMap<String, T>();
            map.put(obName, ob);
            intindex = obserList.indexOf(map);
            if(index == -1) {
                obserList.add(map);
            }
        }
    }
    /* 删除观察者 */
    publicvoid detachObserver(String obName) {
        if(obName == null)thrownew NullPointerException();
        synchronized(obserList){
            Iterator<HashMap<String, T>> iteratorMap = obserList.iterator();
            while(iteratorMap.hasNext()) {
                Iterator<Entry<String, T>> iterator = iteratorMap.next().entrySet().iterator();
                while(iterator.hasNext()){
                    if(iterator.next().getKey().equals(obName)){
                        iteratorMap.remove();
                        break;
                    }
                }
            }
        }
    }
     
    /** detach all observers */
    publicvoid detachObservers() {
        synchronized(obserList) {
            obserList.removeAll(obserList);
        }
    }
     
    /** Ruturn the size of observers */
    publicint countObservers() {
        synchronized(obserList) {
            returnobserList.size();
        }
    }
     
    publicabstract void notifyObservers();
     
    publicabstract void notifyObserver(String obserName, booleanflag, Object... objs);
}
/* 被观察者实例 */
publicclass CommonObservable<T extendsObserver> extendsObservable<T> {
        /* 实现抽象方法通知观察者, 第一个参数为观察者名字,第二个参数flag标志表示如果没有找到观察者是否通知其他所有观察者(true是false否),第三个为需要传递的参数 */
    @Override
    publicvoid notifyObserver(String obserName, booleanflag, Object... objs) {
        // TODO Auto-generated method stub
        if(obserName != null&& !(obserName instanceofString)) return;
        for(HashMap<String, T> map : obserList){
            if(map.containsKey(obserName)) {
                ((T)map.get(obserName)).update(objs);
                break;
            }
        }
        if(flag) {
            for(HashMap<String, T> map : obserList){
                Iterator<Entry<String, T>> iterator = map.entrySet().iterator();
                ((T)iterator.next().getValue()).update(objs);
            }
        }
    }
 
    @Override
    publicvoid notifyObservers() {
        // TODO Auto-generated method stub
        notifyObserver(null,false,null,null);
    }
}
/* 使用实例,如:在点击一个Activity中listview数据后进入另一个Activity,此时对另一个Activity作出改动后需要在不重新从服务器中下载数据后能够看到修改状态 */
publicclass FireTrainCoursewareActivity extendsActivity implementsObserver{
     
    @Override
    protectedvoid onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firetrain_courseware);
        /*在oncreate中注册观察者 */
((BMapApiDemoApp)getApplication()).getCommonObservable().attachObserver("FireTrainCourseware",this);
        (ListViewImpl)findViewById(R.id.firetarin_courseware_listview);
        listItem = newArrayList<HashMap<String,Object>>();
        simpleAdapter = newSimpleAdapter(FireTrainCoursewareActivity.this,
                listItem, R.layout.list_items_peixun, newString[] {
                "ItemImage","ItemTitle","ItemReadTimes","ItemDownloadTimes"}, newint[] {
                R.id.ItemImage_peixun, R.id.ItemTitle_peixun, R.id.ItemRead_peixun,R.id.ItemLoad_peixun });
        listView.setAdapter(simpleAdapter);
        listView.setOnrefreshListener(this);
        listView.setOnItemClickListener(this);
    }
 
    @Override
    protectedvoid onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        /*最好在ondestory中注销之 */
((BMapApiDemoApp)getApplication()).getCommonObservable().detachObserver("FireTrainCourseware");
    }
/* 在update中更新数据 */
@Override
    publicvoid update(Object... objs) {
        // TODO Auto-generated method stub
        mTempList.get(Integer.parseInt(objs[0].toString())).setDownloadTimes(Integer.parseInt(objs[1].toString()));
        for(inti = 0; i < mAllList.size(); i++) {
            if(mAllList.get(i).getId() == mAllList.get(Integer.parseInt(objs[0].toString())).getId()) {
                mAllList.get(i).setDownloadTimes(Integer.parseInt(objs[1].toString()));
                mAllList.get(i).setReadTimes(mTempList.get(Integer.parseInt(objs[0].toString())).getReadTimes());
            }
        }
    }
}
 
/* 使用观察者实例 在想要修改数据的时候调用notify方法即可 */
((BMapApiDemoApp)getApplication()).getCommonObservable()
            .notifyObserver("FireTrainCourseware",false, getIntent().getIntExtra("position",0), downloadTimes_.getText().toString());

android里的观察者模式