今天完成设计模式的实验,以下为实验内容:
实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
1.画出对应的类图;
2.提交源代码;
// 路面接口
interface Road {
void drive();
}
// 具体路面A:水泥路
class ConcreteRoadA implements Road {
public void drive() {
System.out.println("在水泥路上行驶");
}
}
// 具体路面B:沥青路
class ConcreteRoadB implements Road {
public void drive() {
System.out.println("在沥青路上行驶");
}
}
// 车辆抽象类
abstract class Vehicle {
protected Road road;
public Vehicle(Road road) {
this.road = road;
}
public abstract void drive();
}
// 具体车辆A:Car
class ConcreteVehicleA extends Vehicle {
public ConcreteVehicleA(Road road) {
super(road);
}
public void drive() {
System.out.println("Car 在 " + road);
road.drive();
}
}
// 具体车辆B:Bus
class ConcreteVehicleB extends Vehicle {
public ConcreteVehicleB(Road road) {
super(road);
}
public void drive() {
System.out.println("Bus 在 " + road);
road.drive();
}
}
// 测试类
public class BridgeTest {
public static void main(String[] args) {
Road roadA = new ConcreteRoadA();
Road roadB = new ConcreteRoadB();
Vehicle carA = new ConcreteVehicleA(roadA);
Vehicle busA = new ConcreteVehicleB(roadA);
Vehicle carB = new ConcreteVehicleA(roadB);
Vehicle busB = new ConcreteVehicleB(roadB);
carA.drive();
busA.drive();
carB.drive();
busB.drive();
}
}