Observer design mode of design pattern (callback)

The observer design pattern is what we often call callbacks.

The essence of callback is the passing of an object by reference.

1. Find out the observed person;

2. Define an observer interface. The methods in the interface are events that the observer is interested in;

3. Save the reference of the observer in the observed;

4. When an event occurs, notify the observer and call the method in the observer.

 

Thoughts on writing callbacks:

To expose which kind of data, write the interface in which kind of data;

Write which method to expose which parameter;

The adjustment method is to pass parameters.

 

  Class A Class B

Observed by Observed

B passes an object to A;

In A, use this object to adjust B's method to return parameters.

    //定义一个观察者接口,接口中的方法就是观察者感兴趣的事件;
    public interface OnClickListener {
        void onClick(View v);
    }

    private OnClickListener mOnClickListener;
    //在被观察者中保存观察者的引用;
    public void setOnClickListener(OnClickListener listener) {
        this.mOnClickListener = listener;
    }

 

Guess you like

Origin blog.csdn.net/beita08/article/details/83834487