实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
public class Car implements Vehicle{
@Override
public void drive() {
System.out.println("小轿车行驶在");
}
}
public class CementRoad extends Road{
public CementRoad(Vehicle vehicle) {
super(vehicle);
}
@Override
public void driveOnRoad() {
super.vehicle.drive();
System.out.println("水泥路");
}
}
public class Client {
public static void main(String[] args) {
Road road = new AsphaltRoad(new Car());
road.driveOnRoad();
System.out.println("**************************************************");
Road road1 = new CementRoad(new Bus());
road1.driveOnRoad();
}
}
public abstract class Road {
protected Vehicle vehicle;
public Road(Vehicle vehicle){
this.vehicle = vehicle;
}
public abstract void driveOnRoad();
}
public interface Vehicle {
public void drive();
}
public class AsphaltRoad extends Road{
public AsphaltRoad(Vehicle vehicle) {
super(vehicle);
}
@Override
public void driveOnRoad() {
super.vehicle.drive();
System.out.println("沥青路");
}
}
public class Bus implements Vehicle{
@Override
public void drive() {
System.out.println("公交车行驶在");
}
}