【问题标题】:Error when trying to implement the Bridge pattern in Java尝试在 Java 中实现桥接模式时出错
【发布时间】:2011-12-20 22:07:40
【问题描述】:

我想将 Shape 对象传递给 Vector 或 Raster 等 ShapeImp 对象。尝试从 Circle 和 Square 的构造函数内部传递“this”时出现错误。我想将具体形状传递给 Vector 或 Raster。

Netbeans 在线错误

super(平台, x,y, this, "Circle999");

"在调用超类型构造函数之前不能引用 this 在构造函数中泄漏这个”

package dp.bridge;

//-------Abstraction-------//

//----Abstraction-Specialization----------//
abstract class Shape{

    protected ShapeImpl platform;
    protected String type;

    Shape(String p, int x, int y, Circle s, String type){
        this.type = type;
        if(p.equals("vector"))
            platform = new Vector(x,y,s);
         if(p.equals("raster"))
            platform = new Raster(x,y,s);
    }

    public String getType() {
        return type;
    }

    
     abstract public void draw();
}
class Circle extends Shape{



    Circle(String platform, int x, int y){
        super(platform, x,y, this, "Circle999");
        
    }

    public void draw(){
        System.out.println("Circle: draw()");
        platform.draw();
    }
    
}

class Square extends Shape{

     Square(String platform, int x, int y){
        super(platform, x,y,this, "Square778");
     }

    public void draw(){
        System.out.println("Square: draw()");
        platform.draw();
    }

}

//----Abstract-Implementation------//
interface ShapeImpl{
    public void draw();

}

//--------Concreate implemenations--------//
class Raster implements ShapeImpl{

    int _x;
    int _y;
    Shape s;
    Raster(int x, int y, Shape s){
        _x = x;
        _y = y;
        this.s = s;
    }

    public void draw(){
        System.out.println("Drawing Raster "+s.getType()+ " at (" +_x + "," + _y +")");

    }
}

class Vector implements ShapeImpl{

    int _x;
    int _y;
    Shape s;
    Vector(int x, int y, Shape s){
        _x = x;
        _y = y;
        this.s = s;

    }

    public void draw(){
        System.out.println("Drawing Vector "+s.getType()+ " at (" +_x + "," + _y +")");

    }


}

//-----Client-------//
class Client{

    
    public static void main(String atgsp[]){
       Shape[] shapes= {new Circle("raster", 10, 40), new Square("vector", 2,2)};

        for(Shape s:shapes){
            s.draw();
        }
    }
}

【问题讨论】:

  • 如果对象尚未创建,则不能传递this,因为它是一个空引用。并且当调用所有构造函数时将创建对象(您不能这样做,因为构造函数的一个参数是对尚未创建的对象本身的引用)

标签: java design-patterns bridge


【解决方案1】:

你将一个对象传递给它自己?你不需要这样做(而且你不能,很明显)。超类中的this 仍将解析为当前对象。

因此,不要将this 作为参数传递给超级构造函数,而只需在超级构造函数中使用this new Vector(x, s, this)

【讨论】:

  • 有什么办法解决这个问题吗?希望你能得到我想要在这里做的事情。
  • 谢谢。我认为在超构造函数中传递“this”只会传递 Super 类本身的一个实例。 :) 现在我看到它也通过了 Concrete 类!
猜你喜欢
  • 2012-06-13
  • 1970-01-01
  • 2016-04-30
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 2020-10-28
相关资源
最近更新 更多