mercredi 3 mai 2017

Can someone explain this java example of twin design pattern?

I was studying the twin design pattern. While searching I found this java example in wikipedia.

I cant understand properly how the objects named 'twin' communicate here.

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

Aucun commentaire:

Enregistrer un commentaire