尝试在Java中实现Bridge模式时出错

时间:2011-11-03 06:34:26

标签: java design-patterns bridge

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

行上的Netbeans错误

  

super(platform,x,y,this,“Circle999”);

     

“在调用超类型构造函数之前无法引用它   在构造函数中泄露这个“

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

1 个答案:

答案 0 :(得分:1)

您正在将对象传递给自己?你不需要那样做(而且你不能,无所谓)。超类中的this仍将解析为当前对象。

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