我想在CDI环境中使用桥接模式(Weld,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);
....
}
}
也许某人有更好的解决方案或有一些建议。