实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
类图
源代码
public interface Road {
void driveOnRoad();
}
public class AsphaltRoad implements Road{
@Override
public void driveOnRoad(){
System.out.println("沥青路.....");
}
}
public class ConcreteRoad implements Road{
@Override
public void driveOnRoad(){
System.out.println("水泥路.....");
}
}
public abstract class Vehicle {
protected Road road;
// 构造器接受一个Road实例
public Vehicle(Road road) {
this.road = road;
}
// 抽象方法,由子类实现
public abstract void drive();
}
public class Bus extends Vehicle {
public Bus(Road road) {
super(road);
}
@Override
public void drive() {
System.out.println("公交车");
road.driveOnRoad();
}
}
public class Car extends Vehicle {
public Car(Road road) {
super(road);
}
@Override
public void drive() {
System.out.println("汽车");
road.driveOnRoad();
}
}
public class Main {
public static void main(String[] args) {
// 创建不同类型的路
Road concreteRoad = new ConcreteRoad();
Road asphaltRoad = new AsphaltRoad();
// 创建不同的车并指定行驶的路
Vehicle carOnConcrete = new Car(concreteRoad);
Vehicle busOnAsphalt = new Bus(asphaltRoad);
// 测试
carOnConcrete.drive(); // 输出:汽车 水泥路...
busOnAsphalt.drive(); // 输出:公交车 沥青路...
}
}
标签:桥接,void,模式,Road,Vehicle,public,road From: https://www.cnblogs.com/pinganxile/p/18639632