桥接模式

[实验任务一]:两个维度的桥接模式

用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。

实验要求:

1. 画出对应的类图;

 

2.提交源代码;

public interface Vehicle

{

    public void drive();

}

2 具体的交通工具(ConcreteImplementor)

 

public class Car implements Vehicle

{

    @Override

    public void drive()

    {

        System.out.print("car");

    }

}

public class Bus implements Vehicle

{

    @Override

    public void drive()

    {

        System.out.print("bus");

    }

}

3 抽象的路(Abstraction)

 

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 class CementRoad extends Road

{

    public CementRoad(Vehicle vehicle)

    {

        super(vehicle);

    }

 

    @Override

    public void driveOnRoad()

    {

        super.vehicle.drive();

        System.out.println("行驶在沥青");

    }

}

posted @ 2021-10-10 23:44  Zwyooo  阅读(47)  评论(0编辑  收藏  举报