How do children's classes interact in the Twin Design template?

I was looking into the Twin design pattern. I got the concept, but when it came to implementation, I couldn't fully understand how the child classes interact with each other. I found an example of a "ball game" in java but I couldn't figure it out.

Can you explain how child classes exchange messages or exchange messages? It would be helpful if you can provide one or two simple examples in java.

Image of the structure of dual design templates

+3


source to share


1 answer


The two childs classes can interact with each other as they both make up each other.

Take the following example from the Wikipedia article "Twin Pattern" to understand this:

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;
     }
}

      




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

      

Suppose BallThread wants to extend both Thread and BallItem. But if you see BallThread inherited Thread and created BallItem class. By having a reference to the BallItem class (or by making up the BallItem class), BallThread can call all methods of the BallItem class.

Consequently, BallThread provides multiple inheritance by inheriting from the Thread class and constituting the BallItem class.

0


source







All Articles