菜鸟的博客

纵有疾风起,人生不言弃。

导航

软件设计-Tutorial09

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

类图:

```mermaid
classDiagram
    class Road {
        <<interface>>
        +drive()
    }

    class CementRoad {
        +drive()
    }

    class AsphaltRoad {
        +drive()
    }

    class Vehicle {
        +drive()
    }

    class Car {
        +drive()
    }

    class Bus {
        +drive()
    }

    Road <|-- CementRoad
    Road <|-- AsphaltRoad
    Vehicle <|-- Car
    Vehicle <|-- Bus
    Vehicle --> Road : uses
```

源码:

package Tutorial09v2;

public interface Road {
    void drive();
}

class CementRoad implements Road {
    @Override
    public void drive() {
        System.out.println("在水泥路上行驶");
    }
}

class AsphaltRoad implements Road {
    @Override
    public void drive() {
        System.out.println("在沥青路上行驶");
    }
}
package Tutorial09v2;

public abstract class Vehicle {
    protected Road road;

    protected Vehicle(Road road) {
        this.road = road;
    }

    public abstract void drive();
}

class Car extends Vehicle {
    public Car(Road road) {
        super(road);
    }

    @Override
    public void drive() {
        System.out.print("汽车");
        road.drive();
    }
}

class Bus extends Vehicle {
    public Bus(Road road) {
        super(road);
    }

    @Override
    public void drive() {
        System.out.print("公交车");
        road.drive();
    }
}
package Tutorial09v2;


public class Main {
    public static void main(String[] args) {
        Road cementRoad = new CementRoad();
        Road asphaltRoad = new AsphaltRoad();

        Vehicle carOnCementRoad = new Car(cementRoad);
        Vehicle busOnAsphaltRoad = new Bus(asphaltRoad);

        carOnCementRoad.drive(); // 输出: 汽车在水泥路上行驶
        busOnAsphaltRoad.drive(); // 输出: 公交车在沥青路上行驶
    }
}

 

posted on 2024-11-04 09:30  hhmzd233  阅读(11)  评论(0编辑  收藏  举报