0

我想在 CDI 环境中使用桥接模式(焊接,Java EE 7)这是从维基百科复制粘贴的 CDI 修改(http://en.wikipedia.org/wiki/Bridge_pattern):

/** "Implementor" */
interface DrawingAPI {
    public void drawCircle(double x, double y, double radius);
}

/** "ConcreteImplementor"  1/2 */
@API1
class DrawingAPI1 implements DrawingAPI {
   public void drawCircle(double x, double y, double radius) {
        System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
   }
}

/** "ConcreteImplementor" 2/2 */
@API2
class DrawingAPI2 implements DrawingAPI {
   public void drawCircle(double x, double y, double radius) {
        System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);
   }
}

/** "Abstraction" */
abstract class Shape {
   @Inject
   protected DrawingAPI drawingAPI;

   public abstract void draw();                             // low-level
   public abstract void resizeByPercentage(double pct);     // high-level
}

/** "Refined Abstraction" */
@Cirlce
class CircleShape extends Shape {
   private double x, y, radius;
   public CircleShape(double x, double y, double radius) {
      this.x = x;  this.y = y;  this.radius = radius;
   }

   // low-level i.e. Implementation specific
   public void draw() {
        drawingAPI.drawCircle(x, y, radius);
   }
   // high-level i.e. Abstraction specific
   public void resizeByPercentage(double pct) {
        radius *= pct;
   }
}

现在我在想的是有一些魔法,比如:

   /** "Client" */
    class BridgePattern {

       //here I'd like to have a CircleShape with API2
       @Circle @API2 @Inject
       Shape shape1;

       //here I'd like to have AdvancedShape with API1
       @AdvancedCircle @API1 @Inject
       Shape shape1;
    }

我想到的唯一解决方案是使用 setter 作为实现者:

/** "Client" */
class BridgePattern {
    @Circle @Inject 
    private Shape shape;

    @API2 @Inject
    private DrawingAPI api;

    public void method(){
        shape.setApi(api);
            ....    
    }
}

也许有人有更好的解决方案或有一些建议。

4

0 回答 0