赞
踩
桥接模式(Bridge Pattern)是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立变化。桥接模式通过创
建一个桥接接口,将抽象部分和实现部分连接起来,从而实现两者的解耦。
下面是一个详细的桥接模式案例,假设我们要设计一个图形绘制系统,支持不同类型的图形(如圆形、矩形)和不同的绘制工具(如画笔、画刷)。
// 绘制工具接口
public interface DrawingTool {
void drawCircle(int radius, int x, int y);
void drawRectangle(int width, int height, int x, int y);
}
// 画笔工具 public class Pen implements DrawingTool { @Override public void drawCircle(int radius, int x, int y) { System.out.println("用画笔绘制圆形,半径: " + radius + ", 位置: (" + x + ", " + y + ")"); } @Override public void drawRectangle(int width, int height, int x, int y) { System.out.println("用画笔绘制矩形,宽度: " + width + ", 高度: " + height + ", 位置: (" + x + ", " + y + ")"); } } // 画刷工具 public class Brush implements DrawingTool { @Override public void drawCircle(int radius, int x, int y) { System.out.println("用画刷绘制圆形,半径: " + radius + ", 位置: (" + x + ", " + y + ")"); } @Override public void drawRectangle(int width, int height, int x, int y) { System.out.println("用画刷绘制矩形,宽度: " + width + ", 高度: " + height + ", 位置: (" + x + ", " + y + ")"); } }
// 图形抽象类
public abstract class Shape {
protected DrawingTool drawingTool;
public Shape(DrawingTool drawingTool) {
this.drawingTool = drawingTool;
}
public abstract void draw();
}
// 圆形 public class Circle extends Shape { private int radius; private int x; private int y; public Circle(int radius, int x, int y, DrawingTool drawingTool) { super(drawingTool); this.radius = radius; this.x = x; this.y = y; } @Override public void draw() { drawingTool.drawCircle(radius, x, y); } } // 矩形 public class Rectangle extends Shape { private int width; private int height; private int x; private int y; public Rectangle(int width, int height, int x, int y, DrawingTool drawingTool) { super(drawingTool); this.width = width; this.height = height; this.x = x; this.y = y; } @Override public void draw() { drawingTool.drawRectangle(width, height, x, y); } }
public class BridgePatternDemo { public static void main(String[] args) { Shape circleWithPen = new Circle(10, 50, 50, new Pen()); circleWithPen.draw(); Shape circleWithBrush = new Circle(10, 50, 50, new Brush()); circleWithBrush.draw(); Shape rectangleWithPen = new Rectangle(20, 30, 100, 100, new Pen()); rectangleWithPen.draw(); Shape rectangleWithBrush = new Rectangle(20, 30, 100, 100, new Brush()); rectangleWithBrush.draw(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。