桥接模式主要的场景是数据库连接
首先定义一个接口
public interface DrawAPI {
public void drawCircle(int radius,int x,int y);
}
接口的不同的情景的实现
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("绿色圆,圆心(" + x +","+ y +")");
}
}
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("红色圆,圆心(" + x +","+ y +")");
}
}
定义桥
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
public class Circle extends Shape {
private int x,y,radius;
public Circle(int x,int y,int radius,DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
@Override
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
通过持有接口对象的方式适应不同的场景
主函数测试:
public class Main {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100,10,new RedCircle());
Shape greenCircle = new Circle(100,100,10,new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
}