11.6
实验9:桥接模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解桥接模式的动机,掌握该模式的结构;
2、能够利用桥接模式解决实际问题。
[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
1、Vehicle.java
package org.example.shiyanjiu;
public interface Vehicle {
public void drive();
}
2、Bus.java
package org.example.shiyanjiu;
public class Bus implements Vehicle{
@Override
public void drive(){
System.out.println("公交车行驶在");
}
}
3、Car.java
package org.example.shiyanjiu;
public class Car implements Vehicle{
@Override
public void drive(){
System.out.println("小轿车行驶在");
}
}
4、Road.java
package org.example.shiyanjiu;
public abstract class Road {
protected Vehicle vehicle;
public Road(Vehicle vehicle){
this.vehicle=vehicle;
}
public abstract void driveOnRoad();
}
5、CementRoad.java
package org.example.shiyanjiu;
public class CementRoad extends Road{
public CementRoad(Vehicle vehicle){
super(vehicle);
}
@Override
public void driveOnRoad(){
super.vehicle.drive();
System.out.println("水泥路");
}
}
6、AsphaltRoad.java
package org.example.shiyanjiu;
public class AsphaltRoad extends Road{
public AsphaltRoad(Vehicle vehicle){
super(vehicle);
}
@Override
public void driveOnRoad(){
super.vehicle.drive();
System.out.println("沥青路");
}
}
7、Client.java
package org.example.shiyanjiu;
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();
}
}