您的位置:首页 > 编程语言 > Java开发

Java Bridge Pattern(桥接模式)

2017-09-29 00:58 267 查看

Java Bridge Pattern(桥接模式)

桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。

这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。


优点: 1、抽象和实现的分离。 2、优秀的扩展能力。 3、实现细节对客户透明。

缺点:桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。


创建桥接实现接口。

/**
* 1. 创建桥接实现接口。
* @author mazaiting
*/
public interface DrawAPI {
/**
* 画圆
* @param radius 半径
* @param x 圆心横坐标
* @param y 圆心纵坐标
*/
void drawCircle(int radius, int x,int y);
}

创建实现了 DrawAPI 接口的实体桥接实现类。

/**
* 2. 创建实现了 DrawAPI 接口的实体桥接实现类。
* @author mazaiting
*/
public class GreenCircle implements DrawAPI{

public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius +", x: " +x+", y: "+ y +"]");
}

}

/**
* 2. 创建实现了 DrawAPI 接口的实体桥接实现类。
* @author mazaiting
*/
public class RedCircle implements DrawAPI{

public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: "
+ radius +", x: " +x+", y: "+ y +"]");
}

}

使用 DrawAPI 接口创建抽象类 Shape。

/**
* 3. 使用 DrawAPI 接口创建抽象类 Shape。
* @author mazaiting
*/
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
/**
* 绘画
*/
public abstract void draw();
}

创建实现了 Shape 接口的实体类。

/**
* 4. 创建实现了 Shape 接口的实体类。
* @author mazaiting
*/
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(radius, x, y);
}

}

主函数验证

public class Client {
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, y: 100]
Drawing Circle[ color: green, radius: 10, x: 100, y: 100]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: