Android中观察者模式(Observable)的理解

对于观察者模式还是第一次接触,今天在上网看了些资料了解了一下,大意了解了……

定义:“定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变的时候,所有依赖于它的对象都将得到通知,并自动更新”,这就是所谓的观察者模式,照意思理解那么就一定会有观察者和被观察者了,在Java1.2之后,提供了两个类,即Observable被观察者,Observer观察者;

在Android中也提供了一个类Observable用于观察者模式,下面看看Observable 的源码便可以大意理解了。

/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.database; import java.util.ArrayList; /** * Provides methods for (un)registering arbitrary observers in an ArrayList. */ public abstract class Observable { /** * The list of observers. An observer can be in the list at most * once and will never be null. */ protected final ArrayList mObservers = new ArrayList(); /** * Adds an observer to the list. The observer cannot be null and it must not already * be registered. * @param observer the observer to register * @throws IllegalArgumentException the observer is null * @throws IllegalStateException the observer is already registered */ public void registerObserver(T observer) { if (observer == null) { throw new IllegalArgumentException("The observer is null."); } synchronized(mObservers) { if (mObservers.contains(observer)) { throw new IllegalStateException("Observer " + observer + " is already registered."); } mObservers.add(observer); } } /** * Removes a previously registered observer. The observer must not be null and it * must already have been registered. * @param observer the observer to unregister * @throws IllegalArgumentException the observer is null * @throws IllegalStateException the observer is not yet registered */ public void unregisterObserver(T observer) { if (observer == null) { throw new IllegalArgumentException("The observer is null."); } synchronized(mObservers) { int index = mObservers.indexOf(observer); if (index == -1) { throw new IllegalStateException("Observer " + observer + " was not registered."); } mObservers.remove(index); } } /** * Remove all registered observer */ public void unregisterAll() { synchronized(mObservers) { mObservers.clear(); } } }

当然这个类只是抽象类,如果我们需要用的话,还需要继承 这个类,这有一个方法,通知被观察者进行更新。


观察者模式是软体设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。

实现过程:“注册——通知——撤销注册”

1、观察者

(Observer)将自己注册到被观察对象(Subject)中,被观察对象将观察者存放在一个容器(Container)里。

2、被观察对象

被观察对象发生了某种变化,从容器中得到所有注册过的观察者,将变化通知观察者。


你可能感兴趣的:(Android中观察者模式(Observable)的理解)