画类图
具体代码实现
//Road.java
package org.example.design007;
public abstract class Road {
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
protected Vehicle vehicle;
public abstract void drive();
}
//LiQing.java
package org.example.design007;
public class LiQing extends Road{
@Override
public void drive() {
vehicle.run();
System.out.println("行驶在沥青路上");
}
}
//ShuiNi.java
package org.example.design007;
public class ShuiNi extends Road{
@Override
public void drive() {
vehicle.run();
System.out.println("行驶在水泥路上");
}
}
//Vehicle.java
package org.example.design007;
public interface Vehicle {
public void run();
}
//Bus.java
package org.example.design007;
public class Bus implements Vehicle{
@Override
public void run() {
System.out.print("Bus");
}
}
//Car.java
package org.example.design007;
public class Car implements Vehicle{
@Override
public void run() {
System.out.print("Car");
}
}
//Main.java
package org.example.design007;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Vehicle vehicle=null;
Road road=null;
System.out.println("请选择:1、Bus/沥青路;2、Bus/水泥路;3、Car/沥青路;4、Car/水泥路");
int m=sc.nextInt();
if(m==1){
vehicle=(Vehicle) new Bus();
road=(Road) new LiQing();
}else if(m==2){
vehicle=(Vehicle) new Bus();
road=(Road) new ShuiNi();
}else if(m==3){
vehicle=(Vehicle) new Car();
road=(Road) new LiQing();
}else if(m==4){
vehicle=(Vehicle) new Car();
road=(Road) new ShuiNi();
}else{
System.out.println("不存在这样的行为");
}
road.setVehicle(vehicle);
road.drive();
}
}