po3a  

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

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

 

1.类图 

 

 

1. 源代码

1.Car.java

package test9;

 

public class Car implements Vehicle{

    @Override

    public void drive() {

        System.out.println("小轿车行驶在");

    }

}

 

2.CementRoad.java

package test9;

 

public class CementRoad extends Road{

 

    public CementRoad(Vehicle vehicle) {

        super(vehicle);

    }

 

    @Override

    public void driveOnRoad() {

        super.vehicle.drive();

        System.out.println("水泥路");

    }

}

 

3.Client.java

package test9;

 

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();

    }

}

 

 

4.Road.java

package test9;

 

public abstract class Road {

    protected Vehicle vehicle;

    public Road(Vehicle vehicle){

        this.vehicle = vehicle;

    }

    public abstract void driveOnRoad();

}

 

 

5.Vehicle.java

package test9;

 

public interface Vehicle {

    public void drive();

}

 

6.AsphaltRoad.java

package test9;

 

public class AsphaltRoad extends Road{

    public AsphaltRoad(Vehicle vehicle) {

        super(vehicle);

    }

 

    @Override

    public void driveOnRoad() {

        super.vehicle.drive();

        System.out.println("沥青路");

    }

}

 

 

7.Bus.java

package test9;

 

public class Bus implements Vehicle{

 

    @Override

    public void drive() {

        System.out.println("公交车行驶在");

    }

}

 

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