【问题标题】:How child classes communicate in Twin Design Pattern?子类如何在双设计模式中进行通信?
【发布时间】:2017-09-04 13:24:55
【问题描述】:

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

您能解释一下子类是如何交流或交换消息的吗? 如果您能提供一两个简单的 java 示例,将会很有帮助。

Image of twin design pattern structure

【问题讨论】:

    标签: java design-patterns subclass multiple-inheritance


    【解决方案1】:

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

    让我们以Wikipedia article "Twin pattern" 中的以下示例来理解这一点:

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

    假设 BallThread 想要同时扩展 Thread 和 BallItem。但是如果你看到,BallThread 继承了 Thread 并组成了一个 BallItem 类。通过引用 BallItem 类(或组合 BallItem 类),BallThread 将能够调用 BallItem 类的所有方法。

    因此,BallThread 是通过继承 Thread 类并组合 BallItem 类来实现多重继承的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 2020-05-26
      • 2010-10-14
      • 2021-06-25
      • 2011-07-22
      • 2018-10-04
      相关资源
      最近更新 更多