简体   繁体   中英

Calling Interface Method Without Specifying The Class Implementing The Interface

I'd like to call an interface method so it executes in the class implementing that interface. I know I can create an object of that class to call the method, but is there a way to just make one call, then any class implementing the interface would execute the method? Just like protocols in iOS.

For example I have this class for all Firebase operations, and after each operation I'd like to send a message of success to whatever class made the call.

This is the interface class:

      public interface MemberNoteSend {
          public void doneSendNote(String msg);
      }

This is one of the classes implementing the interface:

public class CoachFragment extends Fragment  implements MemberNoteSend {

This is a method in a class to handle Firebase operations:

    public static void sendNoteToMember(String userKey, String note, String source){

    databaseRef.child(Constants.NODE_USERS)
               .child(userKey)
               .child(Constants.NODE_NOTES)
               .push()
               .setValue(noteObj).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            CoachFragment cf = new CoachFragment(); // I DON'T WANT THIS OBJECT
            if(task.isSuccessful()) {
                cf.doneSendNote("Note sent");
            }else{
                cf.doneSendNote("Error");
            }
        }
    });
}

I don't want to make an object of CoachFragment class because this method can be called from more than one fragment of activity. I'm open to other ways to achieve this functionality.

after each operation I'd like to send a message of success to whatever class made the call.

So it's not any . The proper way to do that (IMHO) is to use something like:

public static void sendNoteToMember(final MemberNoteSend sender, String userKey, String note, String source) {
    // ...
    if (task.isSuccessful()) {
        sender.doneSendNote("Note sent");
        // ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM