The Observer pattern

The Observer pattern assumes that there is an object that sends a message, and another object that receives it. The following diagram shows how a class hierarchy can be organized to implement this approach:

The Activity class implements the OnClickListener interface and contains an instance of the Button class, while the Button class contains the performClick method that invokes the onClick method of an instance of the OnClickListener class, if it is not null. The onClick method of the activity will then be invoked. In this way, an instance of the Activity class will be notified when a user clicks on the button.

The following example code shows how this approach works.

The ObserverActivity contains an instance of the Button class and invokes the setOnClickListener method:

class ObserverActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_observer)
findViewById<Button>(R.id.button).setOnClickListener {
Toast.makeText(this, "Clicked!", Toast.LENGTH_LONG).show()
}
}
}

The setOnClickListener method looks as follows:

public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}

The performClick method invokes the onClick function, as follows:

public boolean performClick() {
////......
final boolean result;
final ObserverInfo li = mObserverInfo;
if (li != null && li.mOnClickObserver != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickObserver.onClick(this);
result = true;
} else {
result = false;
}
///........
return result;
}

This shows that the performClick method invokes the onClick method if a reference of the OnClickObserver type is not null.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.120.187