以下是一个简单的桥接模式示例,假设有一个 Shape 类和一个 Color 类,需要将它们分离开来,从而能够使用不同的颜色来填充不同形状的图形。具体实现如下:
// Color.java
public interface Color {
public void fill();
}
// RedColor.java
public class RedColor implements Color {
public void fill() {
System.out.println("Fill with red color.");
}
}
// Shape.java
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
public abstract void draw();
}
// Circle.java
public class Circle extends Shape {
public Circle(Color color) {
super(color);
}
public void draw() {
System.out.println("Draw a circle.");
color.fill();
}
}
// Rectangle.java
public class Rectangle extends Shape {
public Rectangle(Color color) {
super(color);
}
public void draw() {
System.out.println("Draw a rectangle.");
color.fill();
}
}
// Main.java
public class Main {
public static void main(String[] args) {
Color red = new RedColor();
Shape circle = new Circle(red);
Shape rectangle = new Rectangle(red);
circle.draw();
rectangle.draw();
}
}