标签:桥接 void class 软件设计 实验 Vehicle public Road
实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
1.
2.// 抽象类:车
abstract class Vehicle {
protected Road road;
public void setRoad(Road road) {
this.road = road;
}
public abstract void drive();
}
// 具体类:小汽车
class Car extends Vehicle {
@Override
public void drive() {
road.driveVehicle(this);
}
}
// 具体类:公交车
class Bus extends Vehicle {
@Override
public void drive() {
road.driveVehicle(this);
}
}
// 抽象类:路
abstract class Road {
public abstract void driveVehicle(Vehicle vehicle);
}
// 具体类:水泥路
class ConcreteRoad1 extends Road {
@Override
public void driveVehicle(Vehicle vehicle) {
System.out.println("Driving " + vehicle.getClass().getSimpleName() + " on Concrete Road.");
}
}
// 具体类:沥青路
class ConcreteRoad2 extends Road {
@Override
public void driveVehicle(Vehicle vehicle) {
System.out.println("Driving " + vehicle.getClass().getSimpleName() + " on Asphalt Road.");
}
}
// 客户端代码
public class BridgePatternDemo {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle bus = new Bus();
Road road1 = new ConcreteRoad1();
Road road2 = new ConcreteRoad2();
car.setRoad(road1);
car.drive();
bus.setRoad(road2);
bus.drive();
}
}
标签:桥接,
void,
class,
软件设计,
实验,
Vehicle,
public,
Road
From: https://www.cnblogs.com/xuan-2004/p/18572673