android开发笔记之监听者模式

1.一个监听接口的小Demo

package com.example.testcomparator;

public class ListenerManager {
	
	private Listener myListener = null;
	private boolean state;
	
	public void setListener(Listener myListener){
		this.myListener = myListener;
	}
	
	public void setState(boolean state){
		this.state = state;
	}
	
	public void doWorks(){
		if(myListener != null){
			myListener.run(state);
		}
	}
	
	public interface Listener{
		public void run(boolean state);
	}
}


package com.example.testcomparator;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity implements ListenerManager.Listener, 
																OnClickListener {
	
	public static final String TAG = "TEST_COMPARATOR";
	
	private TextView tv1 =null;
	private TextView tv2 =null;
	
	private int clickCount = 0;
	
	private ListenerManager listenerManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();		
	}

	private void init() {
		// TODO Auto-generated method stub
		tv1 = (TextView) findViewById(R.id.tv1);
		tv1.setOnClickListener(this);
		tv2 = (TextView) findViewById(R.id.tv2);

		tv1.setText("请点击我");
		tv2.setText("我是监听点击后的显示结果噢,亲");
		
		listenerManager = new ListenerManager();
		listenerManager.setListener(this);
	}

	@Override
	public void run(boolean state) {
		// TODO Auto-generated method stub
		if(state){
			tv2.setText("亲,您点击了:"+clickCount+"次"+",是偶数次噢");
		}else{
			tv2.setText("亲,您点击了:"+clickCount+"次"+",是奇数次噢");
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if(view == tv1){
			clickCount ++;
			if(clickCount%2 ==  0){
				listenerManager.setState(true);
				listenerManager.doWorks();
			}else{
				listenerManager.setState(false);
				listenerManager.doWorks();
			}
		}
	}

}


2.我的理解:

那么,监听者模式到底有什么用呢?

        我的理解是将一个行为操作放到后面来实现,并且此行为操作还可以改变。哈哈,看这个是不是眼熟啊,不错,如果你还记得策略模式的话,对,这就是一个简单的策略模式。


3.参考资料:

(1) java中的监听者模式

http://blog.csdn.net/yjkwf/article/details/7327757

(2)



你可能感兴趣的:(java,android,监听者模式)