簡體   English   中英

如何使用接口在Java中的兩個類之間進行通信?

[英]How is it possible to communicate between two classes in Java using an interface?

我已經在這里閱讀了一些類似的主題,但是沒有一個回答我的問題。 有人說您甚至不能做到這一點,因為我在這種情況下無法完成自己的課程,所以這不是一件好事。

這里是簡單的代碼。 將每個塊視為一個單獨的類。


public interface Interface {

    void printMessage(String meddelande);

}

public class Model implements Interface {

    String message = "hej!";

    public static void main(String[] args) {

        Model model1 = new Model();

        View view1 = new View();

         model1.printMessage(model1.message); //Ska jag anropa funktionen såhär ens?

    }

    public void printMessage(String str) {

    }

}

public class View implements Interface {

    printMessage(String str) {

    }

}

那么,現在如何在不讓類彼此了解的情況下從視圖類中調用視圖以打印此字符串呢? 不允許將model-objekt的引用發送到視圖對象。 ;

我建議您使用依賴項注入,例如:

public class Model {

    String message = "hej!";
    Interface printer;

    public void Model(Interface printer) {
        printer = printer;
    }

    public static void main(String[] args) {

         Model model1 = new Model(new View());
         model1.printMessage(model1.message); 

    }

    public void printMessage(String str) {
        printer.printMessage(str);
   }
}

定義接口:

public interface MyInterface {

    void printMessage(String str);

}

定義一個可以觸發通知的類:

public class ClassNotifier {

    MyInterface mInterface;

    public ClassNotifier(MyInterface mInterface) {
        this.mInterface = mInterface;
    }

    public void triggerTheMsg(String msg) {
        if (mInterface != null) {
            mInterface.printMessage(msg);
        }
    }
}

定義一個將通知的類:

public class InformedClass implements MyInterface {

    public static void main(String[] args) throws Exception {
         InformedClass c = new InformedClass();
         ClassNotifier cn = new ClassNotifier(c);
    }

    @Override
    public void printMessage(String newMsg) {
        System.out.println("A new msg is here: " + newMsg);
    }
}

如何運作?:

這被稱為回調函數,類ClassNotifier具有對接口MyInterface的引用,即impl。 因此,每次ClassNotifier調用方法printMessage時,類Informed中的方法printMessage也將被觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM