设计模式之桥接模式

337 阅读1分钟

意图

实现抽象和实现的解耦,因为继承可能导致类的爆炸。

实现

创建桥接实现接口

public interface DrawAPI {
    void drawCircle(int x, int y, int radius);
}

实现接口

public class GreenCircle implements DrawAPI {
    @Override
    public void drawCircle(int x, int y, int radius) {
        System.out.println("DrawCircle [color : green " + x + y + radius + "]");
    }
}
public class RedCircle implements DrawAPI {
    @Override
    public void drawCircle(int x, int y, int radius) {
        System.out.println("DrawCircle [color : red" + x + y + radius + "]");
    }
}

使用DrawAPI实现Shape抽象类

public abstract class Shape {
   protected DrawAPI drawAPI;

   protected Shape(DrawAPI drawAPI) {
        this.drawAPI = drawAPI;
    }
   public abstract void draw();
}

创建实现Shape的实体类

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(x, y, radius);
    }
}

测试

public class BridgePatternDemo {
    public static void main(String[] args) {
        Circle greenCircle = new Circle(10,10, 1, new GreenCircle());
        Circle redCircle = new Circle(0,0, 1, new RedCircle());
        greenCircle.draw();
        redCircle.draw();
    }
}

结果

DrawCircle [color : green 10 10 1]
DrawCircle [color : red 0 0 1]

总结

桥接模式就是为了抽象和实现解耦,以上面的例子来说,正常的情况可能是shape - cirelcle - greencirecle,逐步继承,耦合很大,使用桥接模式解耦。上面例子中circle与greencircle解耦。