使用观察者模式完美实现android程序退出

    android的app程序退出有几种方式:activity队列方式、广播方式。在这里介绍一下我实现该功能的方式--观察者模式。
    方法的大概思路为:建立Activity基类,实现观察者接口,实现监听方法,finish掉本实例;在Application里面单例一个目标对象,当需要关闭程序的时候,调用目标对象的通知方法,通知所有观察者。
    代码如下:
观察者接口
public interface Observer {
	public void update(Subject subject);
}

目标对象基类
public class Subject {
	private List<Observer> observers = new ArrayList<Observer>();
	
	public void attach(Observer observer){
		observers.add(observer);
	}

	public void detach(Observer observer){
		observers.remove(observer);
	}
	
	protected void notifyObservers(){
		for(Observer observer : observers){
			observer.update(this);
		}
	}
}


目标对象子类(实现具体退出方法)
public class ApplicationSubject extends Subject {
	public void exit(){
		notifyObservers();
	}
}

MyApplication类(在Manifest文件中将标签application的name改为本类的全限定名)
public class MyApplication extends Application {

	private static ApplicationSubject applicationSubject;
	
	public ApplicationSubject getApplicationSubject() {
                if(applicationSubject == null) applicationSubject = new ApplicationSubject();
		return applicationSubject;
	}
	
}


Activity基类
public abstract class BaseActivity extends Activity implements Observer {

	public MyApplication app;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		app = (MyApplication) this.getApplication();
		app.getApplicationSubject().attach(this);
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
                app.getApplicationSubject().detach(this);
		super.finish();
	}

	/**
	 * 关闭程序
	 */
	public void close() {
		app.getApplicationSubject().exit();
	};
	
	@Override
	public void update(Subject subject) {
		// TODO Auto-generated method stub
		this.finish();
	}
	
}


写几个测试页面测试一下
public class ATestActivity extends BaseActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		startActivity(new Intent(this, BTestActivity.class));
	}
}
public class BTestActivity extends BaseActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		close(); //在BTestActivity中调用close方法,发现A和B都关闭了
	}
}

你可能感兴趣的:(android,程序退出)