每日随笔——桥接模式

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

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

类图:

 

源码:

BUS

package sc9;


public class Bus implements Transport {
    @Override
    public void run() {
        System.out.print("Bus");
    }
}
Car
package sc9;

public class Car implements Transport{
    @Override
    public void run() {
        System.out.print("Car");
    }
}
Road
package sc9;

public abstract class Road {
    protected Transport transport;
    public void setTransport(Transport tr) {
        this.transport=tr;
    }
    public abstract void drive();
}
Transport
package sc9;

public interface Transport {
    public void run();
}
shuini
package sc9;

public class Shuini extends Road{
    public void drive() {
        transport.run();
        System.out.println("行驶在水泥路");
    }
}
main
package sc9;

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Transport transport = null;
        Road road = null;
        System.out.println("请选择:1、Car/水泥路  2、Car/沥青路  3、Bus/水泥路  4、Bus/沥青路");
        Scanner input=new Scanner(System.in);
        int i=input.nextInt();
        if(i==1) {
            transport=(Transport)new Car();
            road=(Road)new Shuini();
        }else if(i==2) {
            transport=(Transport)new Car();
            road=(Road)new LiQing();
        }else if(i==3){
            transport=(Transport)new Bus();
            road=(Road)new Shuini();
        }else if(i==4) {
            transport=(Transport)new Bus();
            road=(Road)new LiQing();
        }else {
            System.out.println("输入无效!");
        }
        road.setTransport(transport);
        road.drive();
    }
}
LiQing
package sc9;

public class LiQing extends Road{
    public void drive() {
        transport.run();
        System.out.println("行驶在沥青路");
    }
}

 

posted @ 2023-11-14 23:27  伽澄  阅读(3)  评论(0编辑  收藏  举报