桥梁模式的Java实现与UML类图
桥梁模式(Bridge Pattern)在Java中的实现及其UML类图是软件设计中常见的一种结构型模式。桥梁模式通过将抽象部分与实现部分分离,使它们可以独立变化。这种模式涉及一个抽象类和一个具体实现类,通过组合而不是继承的方式来实现代码的可扩展性。下面是桥梁模式的具体实现代码:
// 抽象类
abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract void draw();
}
// 具体实现类
class Circle extends Shape {
public Circle(Color color) {
super(color);
}
public void draw() {
System.out.print("Drawing Circle with color ");
color.fill();
}
}
interface Color {
void fill();
}
class RedColor implements Color {
public void fill() {
System.out.println("red.");
}
}
class GreenColor implements Color {
public void fill() {
System.out.println("green.");
}
}
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(new RedColor());
Shape greenCircle = new Circle(new GreenColor());
redCircle.draw();
greenCircle.draw();
}
}
UML类图如下所示:
Shape
是抽象类,具有抽象方法draw()
,并且持有Color
接口的引用。Circle
类是Shape
的具体实现类,实现了draw()
方法。Color
接口有fill()
方法,RedColor
和GreenColor
是其具体实现类。
通过这种方式,桥梁模式使得抽象部分和实现部分可以独立地变化,增加了系统的灵活性。
47.53KB
文件大小:
评论区