您好,我在这里阅读了一些类似的主题,但没有一个回答我的问题。有人说你甚至不能这样做,这不是一件好事,因为在这种情况下我无法完成我的类(class)。
这是一些简单的代码。将每个 block 视为一个单独的类。
<小时/>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) {
}
}
<小时/>
那么,现在如何能够在类彼此不了解的情况下让 View 从模型类打印此字符串呢?不允许将模型对象的引用发送到 View 对象。 ; (
最佳答案
定义接口(interface):
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 具有对接口(interface) MyInterface 的引用,该接口(interface)是 impl。由Informed类来实现,所以每次ClassNotifier调用printMessage方法时,Informed类中的printMessage方法也会被触发。
关于java - Java 中的两个类之间如何使用接口(interface)进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36180180/