??桥接是用于把抽象化与实现化解耦,使得二者可以独立变化。这种设计模式属于结构性模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的耦合。
这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。
/**
* 桥接模式 画图类接口
*
* @author zt1994 2021/4/3 14:55
*/
public interface DrawAPI {
/**
* 画圆
*
* @param radius
* @param x
* @param y
*/
void drawCircle(int radius, int x, int y);
}
/**
* 画红圆实现类
*
* @author zt1994 2021/4/3 14:57
*/
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 + "]");
}
}
/**
* 画绿圆实现类
*
* @author zt1994 2021/4/3 14:57
*/
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 + "]");
}
}
/**
* DrawAPI实现的抽象类shape
*
* @author zt1994 2021/4/3 15:00
*/
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
public abstract void draw();
}
/**
* 实现了 Shape 抽象类的实体类
*
* @author zt1994 2021/4/3 15:02
*/
public class Circle extends Shape {
private int x;
private int y;
private int 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);
}
}
/**
* 桥接模式测试类
*
* @author zt1994 2021/4/3 15:04
*/
public class BridgePatternTest {
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]
原文:https://www.cnblogs.com/zt19994/p/15086088.html