package level2.exercise.exercise06;
public class exercise {
public static void main(String[] args) {
// Person harry = new Person("harry",new Vehicle().getHorse());
// harry.getVehicles().work();
// harry.setVehicles(new Vehicle().getBoat());
// harry.getVehicles().work();
Person person = new Person("tang");
person.comm();
person.passRiver();
person.comm();
person.passRiver();
person.comm();
person.passRiver();
person.passRiver();
person.passRiver();
person.passMount();
}
}
interface Vehicles{
public void work();
}
class Horse implements Vehicles{
@Override
public void work() {
System.out.println("普通情况下,使用马...");
}
}
class Boat implements Vehicles{
@Override
public void work() {
System.out.println("过河的时候,使用船...");
}
}
class Fly implements Vehicles{
@Override
public void work() {
System.out.println("过火焰山的时候,使用飞机...");
}
}
class VehicleFactory{
private static Horse horse;
// 使用静态方法,通过类名就可以调用,不需要实例化对象
public static Vehicles getHorse(){
// 认为从始到终都使用同一匹马 不需要每次调用方法都新创建对象 - 创建一个静态属性
if(horse==null){
horse = new Horse();
}
return horse;
// return new Horse();
}
public static Vehicles getBoat(){
return new Boat();
}
public static Vehicles getFly(){
return new Fly();
}
}
class Person{
private String name;
private Vehicles vehicles;
// 提供普通情况下 执行的方法
public void comm(){
if(!(vehicles instanceof Horse)){ // 如果还没有交通工具 再创建对象并赋值给私有属性
vehicles = VehicleFactory.getHorse();
}
vehicles.work(); // 再调用方法(向上转型)
// Vehicles horse = VehicleFactory.getHorse(); // 从工厂中 拿到对象 对象调用方法
// horse.work();
}
// 提供过河情况下 执行的方法
public void passRiver(){
if(!(vehicles instanceof Boat)){ // 如果还没有交通工具 再创建对象
vehicles = VehicleFactory.getBoat();
}
vehicles.work(); // 再调用方法
// Vehicles boat = VehicleFactory.getBoat();
// boat.work();
}
public void passMount(){
if (!(vehicles instanceof Fly)){
vehicles = VehicleFactory.getFly();
}
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
java练习01
于 2022-02-09 20:19:59 首次发布