设计模式之桥接模式

定义:将抽象部分与实现部分分离,使它们都可以独立的变化。桥接模式的主要目的是将一个对象的变化因素抽象出来,不是通过类继承的方式来满足这个因素的变化,而是通过对象组合的方式来依赖因素的抽象,这样当依赖的因素的具体实现发生变化后,而我们的具体的引用却不用发生改变,因为我们的对象是依赖于抽象的,而不是具体的实现。

结构图:

1.创建桥接实现接口:

public interface DrawAPI
{
public void drawCircle(int radius, int x, int y);
}
2.创建实现了 DrawAPI 接口的实体桥接实现类:

1
2
3
4
5
6
public class GreenCircle implements DrawAPI 
{
public Override void drawCircle(int radius, int x, int y)
{
}
}

3.使用 DrawAPI 接口创建抽象类 Shape:

1
2
3
4
5
6
7
8
9
public abstract class Shape 
{
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI)
{
this.drawAPI = drawAPI;
}
public abstract void draw();
}

4.创建实现了 Shape 接口的实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
}

public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}