For example; when we are saving record, generally we are creating a save function like below;
public class Person { public int Id; public String FirstName; public String LastName; public void Save() { // save person to database ... ... ... return this.Id; } }and save object like below:
Person person = new Person(); person.FirstName = firstName; person.LastName = lastName; ... ... ... long id = person.Save();and wait return value from function to get record id or any errors. It looks ok.
What about if we think in an event-driven paradigm. Create person object, set properties and call save method. And don't care about the return values. Now we are expecting an information from handler "Hey, person has been saved and record id is 99".
Let's start.
First, we are creating a listener interface for save event which is implemented from EventListener
public interface PersonSaveListener extends EventListener { public void onPersonSave(long id); }After that, we are adding PersonSaveListener object and it's setter method to our person class
private PersonSaveListener mPersonSaveListener; public void setPersonSaveListener(PersonSaveListener listener) { mPersonSaveListener = listener; }And we are adding fire event code blocks to our save method
public void Save() { // save person ... ... ... // check save event if (mPersonSaveListener != null) { // fire save event mPersonSaveListener.onPersonSave(this.Id); } }That's all.
Now, save person with event.
// create person instance Person person = new Person(); // set on save listener person.setPersonSaveListener(personSaveListener); // set properties person.FirstName = "First name"; person.LastName = "Last Name"; ... ... ... // save person person.Save();and
personSaveListener
object which we have set:
PersonSaveListener personSaveListener = new PersonSaveListener() { public void onPersonSave(long id) { // person saved and we get record id // do something with id } };
0 comments:
Post a Comment