今天做了桥接模式---两个维度的桥接模式的实验,最后成功了解了桥接模式的运行原理和优缺点。
下面先简要介绍一下桥接模式:
桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(interface)模式。
下面是实验要求以及代码部分:
两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
1. 画出对应的类图;
代码部分;
public class Bus implements Vehicle
{
@Override
public void drive()
{
System.out.print("大巴");
}
}
public class Car implements Vehicle
{
@Override
public void drive()
{
System.out.print("小轿车");
}
}
public class CementRoad extends Road
{
public CementRoad(Vehicle vehicle)
{
super(vehicle);
} @Override
public void driveOnRoad()
{
super.vehicle.drive();
System.out.println("行驶在水泥路");
}
}
public class main {
public static void main(String[] args) {
Road road = new CementRoad(new Car());
road.driveOnRoad();
}
}
public abstract class Road
{
protected Vehicle vehicle; public Road(Vehicle vehicle)
{
this.vehicle = vehicle;
} public abstract void driveOnRoad();
}
public class UnpavedRoad extends Road
{
public UnpavedRoad(Vehicle vehicle)
{
super(vehicle);
} @Override
public void driveOnRoad()
{
super.vehicle.drive();
System.out.println("行驶在石子路");
}
}
public interface Vehicle {
public void drive();}