Search code examples
javaandroiddrupaldrupal-7

Java Distributing event to classes


I am developing an android app for invoice management. Every invoice is linked to a client. And if an invoice becomes overdue a notification is generated.

Now What I wanted is when a client is deleted I want to delete all his/her invoices, payments and notifications.

For that I created a hook pattern like drupal (As I was previously a drupal developer). Following code tells how this patter works.

How hooks are called :

public void callClientDeletedHooks(ClientNew client) {
        final ArrayList<Object> frArr = HookClasses.getClasses();

        if (frArr != null && !frArr.isEmpty()) {
            for (Object frg : frArr) {
                try {
                    if (frg instanceof Hooks.ClientDeletedHook) {
                        Hooks.ClientDeletedHook hooks = (Hooks.ClientDeletedHook) frg;
                        hooks.clientDeleted(client, getActivity());
                    }
                } catch (NoSuchMethodError e) {
                    e.printStackTrace();
                }
            }
        }
    }

callClientDeletedHooks is called right after a client is deleted and it gets the object of client being deleted. Finally this object is distributed to every class that implement that hook.

Hook interfaces :

public interface Hooks {

    public interface ClientDeletedHook {
        public void clientDeleted(ClientNew client_new, Context ctx);
    }

    // Place for other hooks
} 

How I am registering the classed that implement the hook

public class HookClasses {

    public static ArrayList<Object> getClasses() {
        ArrayList<Object> fArr = new ArrayList<Object>();

        fArr.add(new NotificationListFragment());
        fArr.add(new BaseInvoicesListFragment());
        fArr.add(new ReturnListFragment());
        fArr.add(new PaymentListFragment());

        return fArr;
    }

}

How I am implementing the hook in class. An Example.

public class NotificationListFragment extends BaseFragment implements
        Hooks.ClientDeletedHook {

    // This hook is called when client deleted

    @Override
    public void clientDeleted(ClientNew client_new, Context ctx) {
        NotificationUtil _iu = NotificationUtil.getInstance(ctx);
        try {
             // Here I am deleting all notification for a client
            _iu.delete_row_from_table("notification", "client_id", ""
                    + client_new.getClient_id());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Now my question is is it the right way to distribute an event like client being deleted to many classes ?


Solution

  • I don't know about drupal pattern but for this type of problems you can take the Observer Pattern in Java. That is the best pattern for that type of problems and you are very near to that pattern.