桥接器模式
内容参考 w3c School
类型:结构性设计模式
应用:软件的图形绘制
目录
UML类图
绘制图形,首先确定形状,然后调用相应的实体进行绘制。绘制圆形-》红色的圆形注入
创建绘制图形的接口 DrawApi
public interface DrawApi {
/**
* 绘制圆形
* @param radius 半径
* @param x X轴位置
* @param y Y轴位置
*/
void drawCircle(int radius,int x,int y);
/**
* 绘制矩形
* @param height 高
* @param width 宽
* @param x X轴
* @param y Y轴
*/
void drawSquare(int height,int width,int x,int y);
}
创新形状的抽象类 Shape
public abstract class Shape {
protected DrawApi drawApi;
protected Shape(DrawApi drawApi) {
this.drawApi = drawApi;
}
/**
* 绘制图形
*/
abstract void draw();
}
Shape 不关心你是什么形状,只提供了一个绘制图形的方法
创建 矩形(Square)和圆形 (Circle)
Square
public class Square extends Shape{
private int height,width,x,y;
public Square( int height, int width, int x, int y,DrawApi drawApi) {
super(drawApi);
this.height = height;
this.width = width;
this.x = x;
this.y = y;
}
@Override
void draw() {
drawApi.drawSquare(height,width,x,y);
}
}
Circle
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
void draw() {
drawApi.drawCircle(radius,x,y);
}
}
创建不同的图形对象
RedCircle
public class RedCircle implements DrawApi{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("[Drawing Red Circle] r="+radius+" ("+x+","+y+")");
}
@Override
public void drawSquare(int height, int width, int x, int y) {
}
}
GreenCircle
public class GreenCircle implements DrawApi{
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("[Drawing Green Circle] r="+radius+" ("+x+","+y+")");
}
@Override
public void drawSquare(int height, int width, int x, int y) {
}
}
BlueSquare
public class BlueSquare implements DrawApi{
@Override
public void drawCircle(int radius, int x, int y) {
}
@Override
public void drawSquare(int height, int width, int x, int y) {
System.out.println("[Drawing Blue Square] width="+width+" height="+height+" ("+x+","+y+")");
}
}
YellowSquare
public class YellowSquare implements DrawApi{
@Override
public void drawCircle(int radius, int x, int y) {
}
@Override
public void drawSquare(int height, int width, int x, int y) {
System.out.println("[Drawing Yellow Square] width="+width+" height="+height+" ("+x+","+y+")");
}
}
测试执行
public class ExecuteMain {
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();
Shape blueSquare = new Square(5,10,100,100,new BlueSquare());
Shape yellowSquare = new Square(5,10,100,100,new YellowSquare());
blueSquare.draw();
yellowSquare.draw();
}
}
[Drawing Red Circle] r=10 (100,100)
[Drawing Green Circle] r=10 (100,100)
[Drawing Blue Square] width=10 height=5 (100,100)
[Drawing Yellow Square] width=10 height=5 (100,100)
Process finished with exit code 0