嗨,我一直在这里阅读一些类似的主题,但没有一个回答我的问题。有人说你甚至不能这样做,这不是一件好事,因为在这种情况下我无法完成我的课程。
这是一些简单的代码。将每个块视为一个单独的类。
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) {
}
}
那么,现在如何才能在类彼此不了解的情况下告诉视图从模型类打印此字符串呢?不允许将模型对象的引用发送到视图对象。 ; (
定义一个接口:
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。由 Informed 类来实现,因此每次 ClassNotifier 调用 printMessage 方法时,Informed 类中的 printMessage 方法也会被触发。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)