1、神马是观察者模式?
定义:
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
适用性:
当一个抽象模型有两个方面,其中一个方面依赖于另一方面。将这二者封装在独立的对象中以使它们可以各自独立地改变和复用。
当对一个对象的改变需要同时改变其它对象,而不知道具体有多少对象有待改变。
当一个对象必须通知其它对象,而它又不能假定其它对象是谁。换言之,你不希望这些对象是紧密耦合的。
<西游记之观察者模式>
唐僧和三个徒弟(八戒、悟空、沙僧)去西天取经,那么唐僧是这三个徒弟的目标对象,因为这三个徒弟要保护他,而三个徒弟可以理解为观察者对象,当唐僧出事了,三个徒弟都会奋力保护之。
2、代码实例:
ServiceObserable.java
观察者类,主要用于对观察者对象进行注册存储,当MainActivity.java 触发点击事件时可对注册的观察者进行通知
package com.example.serviceobservabledemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import android.graphics.Bitmap;
public class ServiceObserable {
ArrayList<ServiceObserableListener> lists;
HashMap<String, ServiceObserableListener> params = new HashMap<String, ServiceObserableListener>();
/**
* 回调通知接口
*/
public static ServiceObserableListener Obserablelistener = null;
public final static String TEST1 = "test1";
public final static String TEST2 = "test2";
public ServiceObserableListener p = null;
/**
* implements this interface to get Collect more event.
*/
public interface ServiceObserableListener {
public void setObserable(String str);
}
/**
* 单例对象实例
*/
public static ServiceObserable options = null;
public static ServiceObserable getInstance() {
if (options == null) {
synchronized (ServiceObserable.class) {
if (options == null) {
options = new ServiceObserable();
}
}
}
return options;
}
public void register(String name,ServiceObserableListener p) {
params.put(name, p);
}
public void unRegister(String name) {
params.remove(name);
}
public void onlyNotify(String name) {
p = params.get(name);
if(p!=null){
params.get(name).setObserable(name);
}
}
public void allNotify(){
Iterator<String> iterator = params.keySet().iterator();
while(iterator.hasNext()) {
p = params.get(iterator.next());
if(p!=null){
p.setObserable("hello world!");
}
}
}
}
MainActivity.java:
package com.example.serviceobservabledemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button mSendAllBtn;
private Button mSendTest1Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendAllBtn = (Button)findViewById(R.id.sendall_btn);
mSendTest1Btn = (Button)findViewById(R.id.sendtest1_btn);
mSendAllBtn.setOnClickListener(this);
mSendTest1Btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.sendall_btn:
//发送给全部注册者
ServiceObserable.getInstance().allNotify();
break;
case R.id.sendtest1_btn:
//发送给TEST1
ServiceObserable.getInstance().onlyNotify(ServiceObserable.TEST1);
break;
}
// TODO Auto-generated method stub
}
}
Test1Activity.java
package com.example.serviceobservabledemo;
import com.example.serviceobservabledemo.ServiceObserable.ServiceObserableListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test1Activity extends Activity implements ServiceObserableListener,OnClickListener{
private Button mT1Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test1_main);
mT1Btn = (Button)findViewById(R.id.test1);
mT1Btn.setOnClickListener(this);
ServiceObserable.getInstance().register(ServiceObserable.TEST1, this);//添加注册
}
@Override
public void setObserable(String str) {
// TODO Auto-generated method stub
System.out.println("str -----> "+str);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Test1Activity.this,Test2Activity.class));
}
}
Test2Activity.java
package com.example.serviceobservabledemo;
import com.example.serviceobservabledemo.ServiceObserable.ServiceObserableListener;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test2Activity extends Activity implements ServiceObserableListener,OnClickListener{
private Button mT2Btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2_main);
mT2Btn = (Button)findViewById(R.id.test2);
mT2Btn.setOnClickListener(this);
ServiceObserable.getInstance().register(ServiceObserable.TEST2, this);//添加注册
}
@Override
public void setObserable(String str) {
// TODO Auto-generated method stub
System.out.println("str -----> "+str);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Test2Activity.this,MainActivity.class));
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/sendtest1_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送给test1" />
<Button
android:id="@+id/sendall_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送全部" />
</LinearLayout>
test1_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/btn"
android:layout_below="@+id/btn"
android:layout_marginTop="24dp"
android:text="test1" />
</LinearLayout>
test2_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/test2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/btn"
android:layout_below="@+id/btn"
android:layout_marginTop="24dp"
android:text="test2" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.serviceobservabledemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.serviceobservabledemo.Test1Activity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Test2Activity" />
<activity android:name=".MainActivity" />
</application>
</manifest>