[实验任务一]:两个维度的桥接模式
用桥接模式实现在路上开车这个问题,其中,车可以是car或bus,路可以是水泥路或沥青路。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
Vehicle.java
package qiaojie;
public interface Vehicle {
public void run();
}
Road.java
package qiaojie;
public abstract class Road {
protected Vehicle vehicle;
public void setVehicle(Vehicle ve) {
this.vehicle=ve;
}
public abstract void drive();
}
Shuini.java
package qiaojie;
public class Shuini extends Road{
public void drive() {
vehicle.run();
System.out.println("行驶在水泥路");
}
}
Liqing.java
package qiaojie;
public class Liqing extends Road{
public void drive() {
vehicle.run();
System.out.println("行驶在沥青路");
}
}
Bus.java
package qiaojie;
public class Bus implements Vehicle{
@Override
public void run() {
System.out.print("Bus");
}
}
Car.java
package qiaojie;
public class Car implements Vehicle{
@Override
public void run() {
System.out.print("Car");
}
}
Main.java
package qiaojie;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Vehicle vehicle = 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) {
vehicle=(Vehicle)new Car();
road=(Road)new Shuini();
}else if(i==2) {
vehicle=(Vehicle)new Car();
road=(Road)new Liqing();
}else if(i==3){
vehicle=(Vehicle)new Bus();
road=(Road)new Shuini();
}else if(i==4) {
vehicle=(Vehicle)new Bus();
road=(Road)new Liqing();
}else {
System.out.println("输入无效!");
}
road.setVehicle(vehicle);
road.drive();
}
}
#include<iostream>
using namespace std;
class transport
{
public :
transport(){}
virtual ~transport(){}
virtual void bedrive()=0;
};
class bus :public transport
{
public:
bus(){}
virtual~bus(){}
void bedrive(){cout<<"bus"<<endl;}
};
class car :public transport
{
public:
car(){}
virtual~car(){}
void bedrive(){cout<<"car"<<endl;}
};
class road
{
public:
road():_instance(NULL){}
virtual~road(){}
void settransport(transport *instance)
{
_instance=instance;
}
virtual void drive()=0;
protected:
transport *_instance;
};
class shuini :public road
{
public:
shuini(){}
virtual~shuini(){}
void drive(){cout<<"行驶在水泥路";_instance->bedrive();}
};
class liqing :public road
{
liqing(){}
virtual~liqing(){}
void drive(){cout<<"行驶在沥青路";_instance->bedrive();}
};
int main()
{
road *ro=new shuini;
transport *tr=new bus;
ro->settransport(tr);
ro->drive();
delete ro;
delete tr;
system("pause");
return 0;
}
3.注意编程规范。
posted @
2024-11-05 14:27
Mini-Q
阅读(
2)
评论()
编辑
收藏
举报