标签:总结 每日 40 class void Road Vehicle public road
软件设计 石家庄铁道大学信息学院
实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
// 车的抽象部分接口
public abstract class Vehicle {
protected Road
road;
public
Vehicle(Road road) {
this.road =
road;
}
public abstract
void drive();
}
// 路的实现部分接口
public interface Road {
void travel();
}
// 具体的车类
public class Car extends Vehicle {
public Car(Road
road) {
super(road);
}
@Override
public void
drive() {
System.out.println("Car is driving on " +
road.getClass().getSimpleName());
road.travel();
}
}
public class Bus extends Vehicle {
public Bus(Road
road) {
super(road);
}
@Override
public void
drive() {
System.out.println("Bus is driving on " +
road.getClass().getSimpleName());
road.travel();
}
}
// 具体的路实现类
public class CementRoad implements Road {
@Override
public void
travel() {
System.out.println("Traveling on Cement Road");
}
}
public class AsphaltRoad implements Road {
@Override
public void
travel() {
System.out.println("Traveling
on Asphalt Road");
}
}
public class BridgeTest {
public static
void main(String[] args) {
Road
cementRoad = new CementRoad();
Road
asphaltRoad = new AsphaltRoad();
Vehicle car =
new Car(cementRoad);
car.drive();
Vehicle bus =
new Bus(asphaltRoad);
bus.drive();
}
}
标签:总结,
每日,
40,
class,
void,
Road,
Vehicle,
public,
road
From: https://www.cnblogs.com/azure011328/p/18543075