代码:
public static void main(String[] args) {
Person2 person=new Person2("唐僧",new Horse());
person.passRiver();
person.onRoad();
}
接口:
interface Vehicles{
public void work();
}
lass Horse implements Vehicles{
@Override
public void work() {
System.out.println("大陆骑马去");
}
}
class Boat implements Vehicles{
@Override
public void work() {
System.out.println("过河坐船去");
}
}
class Person2{
private String name;
private Vehicles Vehicles;
public Person2(String name, Vehicles vehicles) {
this.name = name;
Vehicles = vehicles;
}
public void passRiver() {
if (Vehicles == null) {
Vehicles = VehiclesFactory.getBoat();
}
//过河,先从工厂获取一艘船
Boat boat = VehiclesFactory.getBoat();
boat.work();
}
public void onRoad () {
//判断当前属性是否已经存在
if (Vehicles == null) {
Vehicles = VehiclesFactory.getHorse();
}
//过河,先从工厂获取一艘船
Horse horse = VehiclesFactory.getHorse();
horse.work();
}
}
public class VehiclesFactory {
//写static,可以直接调用方法,不用创建对象
public static Horse getHorse() {
return new Horse();
}
public static Boat getBoat() {
return new Boat();
}
}
结果: