原文连接
译者:smallclover
我的翻译,水平有限,若有错误欢迎指出,谢谢!java
咱们使用桥来解耦(decouple )一个抽象以及该抽象的实现。使用桥以后抽象和实现能够相互独立的改变。这种类型的设计模式来源于结构型模式,它能够经过使用桥结构来解耦抽象类及其实现类。设计模式
这种模式涉及一个接口,它扮演一个桥的角色,使得具体类的功能独立与接口。这两种类型的类能够在不影响对方的状况下改变自身结构。ide
咱们经过下面的例子来演示桥模式的使用。画一个圆使用不一样的颜色,相同的抽象类方法,不一样的桥的具体实现者。this
咱们有一个DrawAPI接口,它扮演一个桥的实现化者的角色,而后会有具体的类RedCircle和GreenCircle实现接口DrawAPI。抽象类Shape将持有DrawAPI对象。BridgePatternDemo,咱们的demo类将使用Shape类画两个不一样颜色的圆。spa
译者注:bridge implementer 这里翻译为桥的实现化者,它不一样于具体的实现,如:继承,实现。这里的实现是指对桥这种概念的具体化,实现化。翻译
建立一个桥的实现化者接口DrawAPI
DrawAPI.java设计
public interface DrawAPI { public void drawCircle(int radius, int x, int y); }
建立具体的类实现DrawApI接口
RedCircle.javacode
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 + "]"); } }
GreenCircle.javahtm
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 + "]"); } }
建立一个抽象类 Shape,该类持有一个DrawAPI接口的引用。
Shape.java对象
public abstract class Shape { protected DrawAPI drawAPI; protected Shape(DrawAPI drawAPI){ this.drawAPI = drawAPI; } public abstract void draw(); }
建立一个具体类实现抽象类Shape。
Circle.java
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); } }
使用Shape和DrawAPI类画两个不一样颜色的圆。
BridgePatternDemo.java
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]