码迷,mamicode.com
首页 > 移动开发 > 详细

android里的观察者模式

时间:2015-01-12 22:36:47      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:

状况:遇到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
/* 观察者 */
public interface Observer {
    void update(Object... objs);
}
/* 被观察者 使用一个抽象类方便扩展 */
public abstract class Observable<T> {
     
     
    public final transient ArrayList<HashMap<String, T>> obserList = new ArrayList<HashMap<String,T>>();
     
    /* 添加观察者 包括名称及本生 */
    public void attachObserver(String obName, T ob) {
        if(obName == null || ob == null) throw new NullPointerException();
        synchronized(obserList) {
            HashMap<String, T> map = new HashMap<String, T>();
            map.put(obName, ob);
            int index = obserList.indexOf(map);
            if(index == -1) {
                obserList.add(map);
            }
        }
    }
    /* 删除观察者 */
    public void detachObserver(String obName) {
        if(obName == null) throw new 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 */
    public void detachObservers() {
        synchronized(obserList) {
            obserList.removeAll(obserList);
        }
    }
     
    /** Ruturn the size of observers */
    public int countObservers() {
        synchronized(obserList) {
            return obserList.size();
        }
    }
     
    public abstract void notifyObservers();
     
    public abstract void notifyObserver(String obserName, boolean flag, Object... objs);
}
/* 被观察者实例 */
public class CommonObservable<T extends Observer> extends Observable<T> {
        /* 实现抽象方法通知观察者, 第一个参数为观察者名字,第二个参数flag标志表示如果没有找到观察者是否通知其他所有观察者(true是false否),第三个为需要传递的参数 */
    @Override
    public void notifyObserver(String obserName, boolean flag, Object... objs) {
        // TODO Auto-generated method stub
        if(obserName != null && !(obserName instanceof String)) 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
    public void notifyObservers() {
        // TODO Auto-generated method stub
        notifyObserver(null, false, null, null);
    }
}
/* 使用实例,如:在点击一个Activity中listview数据后进入另一个Activity,此时对另一个Activity作出改动后需要在不重新从服务器中下载数据后能够看到修改状态 */
public class FireTrainCoursewareActivity extends Activity implements Observer{
     
    @Override
    protected void 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 = new ArrayList<HashMap<String,Object>>();
        simpleAdapter = new SimpleAdapter(FireTrainCoursewareActivity.this,
                listItem, R.layout.list_items_peixun, new String[] {
                "ItemImage", "ItemTitle", "ItemReadTimes","ItemDownloadTimes" }, new int[] {
                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
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        /*最好在ondestory中注销之 */
((BMapApiDemoApp)getApplication()).getCommonObservable().detachObserver("FireTrainCourseware");
    }
/* 在update中更新数据 */
@Override
    public void update(Object... objs) {
        // TODO Auto-generated method stub
        mTempList.get(Integer.parseInt(objs[0].toString())).setDownloadTimes(Integer.parseInt(objs[1].toString()));
        for(int i = 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里的观察者模式

标签:

原文地址:http://blog.csdn.net/u014311037/article/details/42649497

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!