题目要求
- 有一个交通工具接口类Vehicles,有work接口
- 有Horse类和Boat类分别实现Vehicles
- 创建交通工具工厂类,有两个方法分别获得交通工具Horse和Boat
- 有Person类,有name和Vehicles属性,在构造器中为两个属性赋值
- 实例化Person对象“唐僧”,要求一般情况下用Horse作为交通工具,遇到大河时用Boat作为交通工具
public class Homework06 {public static void main(String[] args) {Person person = new Person("唐僧",new Horse());person.common();person.passRiver();}
}
//1.有一个交通工具接口类Vehicles,有work接口
interface Vehicles{void work();
}
//2.有Horse类和Boat类分别实现Vehicles
class Horse implements Vehicles{@Overridepublic void work() {System.out.println("骑马");}
}
class Boat implements Vehicles{@Overridepublic void work() {System.out.println("坐船");}
}
//3.创建交通工具工厂类,有两个方法分别获得交通工具Horse和Boatclass Fork{private static Horse horse = new Horse();//饿汉式,马始终是一匹//将方法做成静态方法容易调动public static Boat getBoat(){//获取Boatreturn new Boat();}public static Horse getHorse(){//获取Horsereturn horse;}
}
//4.有Person类,有name和Vehicles属性,在构造器中为两个属性赋值class Person{private String name;private Vehicles vehicles;public Person(String name, Vehicles vehicles) {this.name = name;this.vehicles = vehicles;}public void passRiver(){//先得到船//判断,当前的vehicles属性时null,就获取一艘船//如何防止始终使用的时传入的马 interface//vehicles instanceof Boat用来判断当前的vehicles是不是Boat//1.vehicles = null:vehicles interface Boat =》 false;//1.vehicles = 马对象:vehicles interface Boat =》 false;//1.vehicles = 船对象:vehicles interface Boat =》 true;if (!(vehicles instanceof Boat)) {vehicles = Fork.getBoat();}vehicles.work();}public void common(){if (!(vehicles instanceof Horse)) {vehicles = Fork.getHorse();}vehicles.work();}
}