首页 > 代码库 > 观察者模式修改

观察者模式修改

状况:遇到android程序中后入栈的一个Activity需要更新之前一个或者两个以上Activity中的数据时使用,或者需要在adapter中修改Activity或者fragment的数据和ui等

[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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//观察者,需要用到观察者模式的类需实现此接口
public interface Observer {
    voidupdate(Object... objs);
}
//被观察者(一个抽象类,方便扩展)
public abstract class Observable {
    
    publicfinal ArrayList<Class<?>> obserList =new ArrayList<Class<?>>();
    
    /** Attach Observer (通过实例注册观察者)
     * <b>Notice:</b> ob can‘t be null ,or it will throw NullPointerException
     * */
    public<T> void registerObserver(T ob) {
        if (ob == null)throw newNullPointerException();
        this.registerObserver(ob.getClass());
    }
    /**
     * Attach Observer(通过Class注册观察者)
     * @param cls
     */
    publicvoid registerObserver(Class<?> cls) {
        if (cls == null)throw newNullPointerException();
        synchronized(obserList) {
            if (!obserList.contains(cls)) {
               obserList.add(cls);
            }
        }
    }
    
    /** Unattach Observer (注销观察者)
     * <b>Notice:</b> 
     * <b>It reverses with attachObserver() method</b>
     * */
    public<T> void unRegisterObserver(T ob) {
        if (ob == null)throw newNullPointerException();
        this.unRegisterObserver(ob.getClass());
    }
    
    /** Unattach Observer(注销观察者,有时候在未获取到实例使用)
     * <b>Notice:</b> 
     * <b>It reverses with attachObserver() method</b>
     * */
    publicvoid unRegisterObserver(Class<?> cls) {
        if(cls == null)throw newNullPointerException();
        synchronized(obserList){
            Iterator<Class<?>> iterator = obserList.iterator();
            while(iterator.hasNext()) {
               if(iterator.next().getName().equals(cls.getName())){
                   iterator.remove();
                   break;
               }
            }
        }
    }
    
    /** detach all observers */
    publicvoid unRegisterAll() {
        synchronized(obserList) {
            obserList.clear();
        }
    }
    
    /** Ruturn the size of observers */
    publicint countObservers() {
        synchronized(obserList) {
            return obserList.size();
        }
    }
    
    /**
     * notify all observer (通知所有观察者,在子类中实现)
     * @param objs
     */
    publicabstract voidnotifyObservers(Object... objs);
    
    /**
     * notify one certain observer (通知某一个确定的观察者)
     * @param cls
     * @param objs
     */
    publicabstract voidnotifyObserver(Class<?> cls, Object... objs);
    
    /**
     * notify one certain observer
     * @param cls
     * @param objs
     */
    publicabstract <T> voidnotifyObserver(T t, Object... objs);
}
//目标被观察者
public class ConcreteObservable extendsObservable {
    privatestatic ConcreteObservable instance =null;
    privateConcreteObservable() {}
    publicstatic synchronizedConcreteObservable getInstance() {
        if (instance == null) {
            instance = new ConcreteObservable();
        }
        return instance;
    }
    
    @Override
    public<T> void notifyObserver(T t, Object... objs) {
        // TODO Auto-generated method stub         if (t == null)throw newNullPointerException();
        this.notifyObserver(t.getClass(), objs);
    }
    @Override
    publicvoid notifyObservers(Object... objs) {
        // TODO Auto-generated method stub         for (Class<?> cls : obserList) {
            this.notifyObserver(cls, objs);
        }
    }
    @Override //通过java反射机制实现调用     public void notifyObserver(Class<?> cls, Object... objs) {
        // TODO Auto-generated method stub         if (cls == null)throw newNullPointerException();
        Method[] methods = cls.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals("update")) {
               try {
                   method.invoke(cls, objs);
                                       break;
               } catch (IllegalArgumentException e) {
                   // TODO Auto-generated catch block                    e.printStackTrace();
               } catch (IllegalAccessException e) {
                   // TODO Auto-generated catch block                    e.printStackTrace();
               } catch (InvocationTargetException e) {
                   // TODO Auto-generated catch block                    e.printStackTrace();
               }
            }
        }
    }
    
}
//使用 (实现Observer接口)
publicclass Text extendsActivity implementsObserver {
   publicvoid onCreate(...) {
       ConcreteObservable.getInstance().registerObserver(Text.class);
       ....
   }
   //实现接口处理   public voidupdate(Object... objs) {
       // 做操作,比如更新数据,更新UI等    }
}

观察者模式修改