桥接模式(Bridge Pattern)是将抽象部分和实现部分分离,使它们可以独立地改变,是一种对象结构型模式。
桥接模式包含如下角色:
桥接模式关键在于如何将抽象化与实现化解耦,使得两者可以独立改变。
抽象化:抽象就是忽略一些信息,将不同的实体当作同样的实体对待。在面向对象中将对象的共同性质抽取出来形成类的过程称之为抽象化的过程
实现化:针对抽象话给出的具体实现,就是实现化,抽象化与实现化是互逆的过程
解耦:解耦就是将抽象化和实现化直接的耦合解脱开,或者说将两者之间的强关联变成弱关联,将两个角色由继承改成关联关系(组合或者聚合)
典型代码:
public interface Implementor
{
public void operationImpl();
}
public abstract class Abstraction
{
protected Implementor impl;
public void setImpl(Implementor impl)
{
this.impl=impl;
}
public abstract void operation();
}
public class RefinedAbstraction extends Abstraction
{
public void operation()
{
//代码
impl.operationImpl();
//代码
}
}
画出不同颜色的圆,DrawAPI 接口的实体类 RedCircle、GreenCircle。Shape 是一个抽象类,例子来自:http://www.runoob.com/design-pattern/bridge-pattern.html
创建桥接接口:
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
接口具体实现类:
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", "+ y +"]");
}
}
public class GreenCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +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;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
public class BridgePatternDemo {
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();
}
}
打印到控制台:
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]