如何使用接口在Java中的两个类之间进行通信? [英] How is it possible to communicate between two classes in Java using an interface?

查看:101
本文介绍了如何使用接口在Java中的两个类之间进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里一直在阅读一些类似的主题,但是没有一个回答我的问题.有人说你甚至不能做到这一点,这不是一件好事,因为在这种情况下我无法完成我的课程.

Hi ive been reading on some similar topics here but none of them answer my question. Some say you cant even do this which is not a good thing since I cant finnish my course in that case.

这里有一些简单的代码.将每个块视为一个单独的类.

Heres som simple code. Think of each block as a separate class.

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的引用发送到视图对象.;(


So, how is it now possible to tel the view to print this string from the model class without the classes knowing about each other? Its not allowed to send a reference of the model-objekt to the view-object. ; (

推荐答案

定义接口:

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也将被触发.


How does it works?:

this is named a callback parttern, the class ClassNotifier has a reference to the interface MyInterface, which is impl. by Informed class to, so every time the ClassNotifier calls the method printMessage, the method printMessage in the class Informed will be triggered too.

这篇关于如何使用接口在Java中的两个类之间进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆