1. 类图:
2.源代码
// 车接口
interface Vehicle {
void drive();
}
// 小汽车类
class Car implements Vehicle {
private String name;
public Car(String name) {
this.name = name;
}
@Override
public void drive() {
System.out.println(name + " is driving on the road.");
}
}
// 公交车类
class Bus implements Vehicle {
private String name;
public Bus(String name) {
this.name = name;
}
@Override
public void drive() {
System.out.println(name + " is driving on the road.");
}
}
// 路接口
interface Road {
void driveOn(Vehicle vehicle);
}
// 水泥路类
class CementRoad implements Road {
@Override
public void driveOn(Vehicle vehicle) {
System.out.println("Driving on cement road with " + vehicle.getClass().getSimpleName());
vehicle.drive();
}
}
// 沥青路类
class AsphaltRoad implements Road {
@Override
public void driveOn(Vehicle vehicle) {
System.out.println("Driving on asphalt road with " + vehicle.getClass().getSimpleName());
vehicle.drive();
}
}
// 测试类
public class BridgePatternTest {
public static void main(String[] args) {
Vehicle car = new Car("Car");
Vehicle bus = new Bus("Bus");
Road cementRoad = new CementRoad();
Road asphaltRoad = new AsphaltRoad();
cementRoad.driveOn(car);
cementRoad.driveOn(bus);
asphaltRoad.driveOn(car);
asphaltRoad.driveOn(bus);
}
}
posted @
2024-11-04 09:20
艾鑫4646
阅读(
1)
评论()
编辑
收藏
举报