软件设计 石家庄铁道大学信息学院
实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
1. 画出对应的类图;
2. 提交源代码;
Bus.java
package ruanshe9;
public class Bus implements Vehicle{
@Override
public void run() {
System.out.print("Bus");
}
}
Car.java
package ruanshe9;
public class Car implements Vehicle{
@Override
public void run() {
System.out.print("Car");
}
}
Liqing.java
package ruanshe9;
public class Liqing extends Road{
public void drive() {
vehicle.run();
System.out.println("行驶在沥青路");
}
}
Road.java
package ruanshe9;
public abstract class Road {
protected Vehicle vehicle;
public void setVehicle(Vehicle ve) {
this.vehicle=ve;
}
public abstract void drive();
}
Shuini.java
package ruanshe9;
public class Shuini extends Road{
public void drive() {
vehicle.run();
System.out.println("行驶在水泥路");
}
}
Test.java
package ruanshe9;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Vehicle vehicle = null;
Road road = null;
System.out.println("1、Car/水泥路 2、Car/沥青路 3、Bus/水泥路 4、Bus/沥青路");
Scanner input=new Scanner(System.in);
int i=input.nextInt();
vehicle=(Vehicle)new Car();
road=(Road)new Shuini();
road.setVehicle(vehicle);
road.drive();
vehicle=(Vehicle)new Car();
road=(Road)new Liqing();
road.setVehicle(vehicle);
road.drive();
vehicle=(Vehicle)new Bus();
road=(Road)new Shuini();
road.setVehicle(vehicle);
road.drive();
vehicle=(Vehicle)new Bus();
road=(Road)new Liqing();
road.setVehicle(vehicle);
road.drive();
}
}
Vehicle.java
package ruanshe9;
public interface Vehicle {
public void run();