实验9:桥接模式

实验9:桥接模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解桥接模式的动机,掌握该模式的结构;

2、能够利用桥接模式解决实际问题。

 

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

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

实验要求:

1. 对应的类图如下;

 

2. 源代码如下;

 

package a9;  
public abstract class Road {  
protected Transport transport;  
public void setTransport(Transport tr) {  
this.transport=tr;  
}  
public abstract void drive();  
}  
package a9;  
public class Liqing extends Road{  
public void drive() {  
transport.run();  
System.out.println("行驶在沥青路");  
}  
} 
package a9;  
public class Shuini extends Road{  
public void drive() {  
transport.run();  
System.out.println("行驶在水泥路");  
}  
}  
package a9;  
public interface Transport {  
public void run();  
}  
package a9;  
public class Bus implements Transport{  
@Override  
public void run() {  
System.out.print("Bus");  
}  
} 
package a9;  
public class Car implements Transport{  
@Override  
public void run() {  
System.out.print("Car");  
}  
}  
package a9;  
import java.util.*;  
public class Client {  
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();  
}  
}  
 

 

 

posted @ 2023-11-25 23:09  杳无音讯  阅读(20)  评论(0编辑  收藏  举报