Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 儿童班级如何以双胞胎设计模式进行沟通?_Java_Design Patterns_Subclass_Multiple Inheritance - Fatal编程技术网

Java 儿童班级如何以双胞胎设计模式进行沟通?

Java 儿童班级如何以双胞胎设计模式进行沟通?,java,design-patterns,subclass,multiple-inheritance,Java,Design Patterns,Subclass,Multiple Inheritance,我在研究双胞胎设计模式。我得到了这个概念,但当涉及到实现时,我无法完全理解子类是如何相互通信的。我在java中找到了一个“球类游戏”的例子,但我仍然无法从中找到答案 您能解释一下子类是如何通信或交换消息的吗? 如果您能提供一到两个简单的java示例,这将非常有用 两个Child类能够相互通信,因为它们都构成了彼此的对象 让我们从以下示例中了解这一点: public class BallItem extends GameItem { BallThread twin; int

我在研究双胞胎设计模式。我得到了这个概念,但当涉及到实现时,我无法完全理解子类是如何相互通信的。我在java中找到了一个“球类游戏”的例子,但我仍然无法从中找到答案

您能解释一下子类是如何通信或交换消息的吗? 如果您能提供一到两个简单的java示例,这将非常有用


两个Child类能够相互通信,因为它们都构成了彼此的对象

让我们从以下示例中了解这一点:

public class BallItem extends GameItem {
     BallThread twin;

     int radius; int dx, dy;
     boolean suspended;

     public void draw(){
        board.getGraphics().drawOval(posX-radius, posY-radius,2*radius,2*radius);
     }

     public void move() { 
       posX += dx; posY += dy; 
     }

     public void click() {
       if (suspended) twin.resume(); else twin.suspend();
       suspended = ! suspended;
     }

     public boolean intersects (GameItem other) {
      if (other instanceof Wall)
       return posX - radius <= other.posX && other.posX <= posX + radius || posY - radius <= other.posY && other.posY <= posY + radius;

      else return false;
     }

     public void collideWith (GameItem other) {
      Wall wall = (Wall) other;
      if (wall.isVertical) dx = - dx; else dy = - dy;
     }
}
假设BallThread想要扩展Thread和BallItem。但如果您看到,BallThread继承了Thread并组成了一个BallItem类。通过引用BallItem类(或组合BallItem类),BallThread将能够调用BallItem类的所有方法

因此,BallThread通过继承Thread类和组合BallItem类来实现多重继承

public class BallThread extends Thread {
   BallItem twin;
   public void run() {
     while (true) {
       twin.draw(); /*erase*/ twin.move(); twin.draw();
     } 
   }
}