概述:
桥接(Bridge)是用于把抽象化与实现化解耦。使得二者可以独立变化。这种类型的设计模式 属于结构型模式,它通过提供抽象化和实现化之间的桥接结构实现二者的解耦。
特点:
桥接模式不是单单使用类继承的方式,而是重点使用类聚合的方式,进行桥接,把抽象的功能点,聚合(注入)到基类中去。
使用场景:
主要解决的就是实现系统需要多维度的功能点,每个维度又有多种变化,多维度多变化的组合实现,使用继承的方式可能会造成类爆炸,扩展不灵活的问题。
试想一下我们现在要实现画一个带颜色的几何图形,颜色有红、绿、n个等等,几何图形有圆形、方形、m个等,假如我们使用继承的方式,那么就是需要n*m个实现类,且如果再加颜色或者集合图形就需要再加实现类,这明显不那么灵活,那么我们需要的就是将颜色和几何图形进行解耦,颜色的扩展实现自己控制,几何图形的扩展自己扩展,二者之间通过桥接的方式进行组合实现。
实现方法:
首先我们创建一个画颜色的接口
public interface DrawAPI {
public void draw();
}
然后创建2个实际画颜色的两个类
public class Red implements DrawAPI{
@Override
public void draw(String shapeName) {
System.out.println(shapeName + " draw red");
}
}
public class Green implements DrawAPI{
@Override
public void draw(String shapeName) {
System.out.println(shapeName + " draw green");
}
}
然后创建一个几何图形的抽象类Shape
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 radius;
public Circle(int radius, DrawAPI drawAPI){
super(drawAPI);
this.radius = radius;
}
@Override
public void draw() {
drawAPI.draw("circle");
}
}
public class Rectangle extends Shape{
// x长 y宽
private int x,y;
public Rectangle(int x, int y, DrawAPI drawAPI){
super(drawAPI);
this.x = x;
this.y = y;
}
@Override
public void draw() {
drawAPI.draw("rectangle");
}
}
接下来创建一个测试类来测试下
public class BridgeTest {
public static void main(String[] args) {
Shape redCircle = new Circle(360,new Red());
Shape greenCircle = new Circle(360,new Green());
redCircle.draw();
greenCircle.draw();
Shape redRectangle = new Rectangle(100,100,new Red());
Shape greenRectangle = new Rectangle(100,100,new Green());
redRectangle.draw();
greenRectangle.draw();
}
}
circle draw red
circle draw green
rectangle draw red
rectangle draw green