两个使用Interface进行通信的独立类 [英] Two independent classes that communicate using an Interface

查看:128
本文介绍了两个使用Interface进行通信的独立类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过实现接口进行两个独立的类通信,如果是,如何进行通信?

Is it possible to have two independent class communicate by implementing an interface, and if so, how?

推荐答案

我认为这里使用接口有点极端,但我假设这是一个更大问题的简化

I think that using interfaces is a little extreme here but i'm assuming this is a simplification of a larger problem

public interface SomeInterface {

    public void giveString(String string);

    public String getString();

}


public class Class1 implements SomeInterface{

    String string;

    public Class1(String string) {
        this.string = string;
    }

    //some code

    @Override
    public void giveString(String string) {
        //do whatever with the string
        this.string=string;

    }

    @Override
    public String getString() {
        return string;
    }



}


public class Class2 implements SomeInterface{

    String string;

    public Class2(String string) {
        this.string = string;
    }

    //some code

    @Override
    public void giveString(String string) {
        //do whatever with the string
        this.string=string;

    }

    @Override
    public String getString() {
        return string;
    }

}


public class Test{

    public static void main(String args[]){
        //All of this code is inside a for loop
        Class1 cl1=new Class1("TestString1");
        Class2 cl2=new Class2("TestString2");

        //note we can just communicate now, no interface
        cl1.giveString(cl2.string);


        //but we can also communicate using the interface
        giveStringViaInterface(cl2,cl1);
    }

    //any class that extended SomeInterface could use this method
    public static void giveStringViaInterface(SomeInterface from, SomeInterface to){
        to.giveString(from.getString());
    }



}

这篇关于两个使用Interface进行通信的独立类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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