我根据@AlexR 的回答创建了以下示例,希望对您有所帮助。
餐厅.java:
package org.example;
public interface Restaurant {
String getName();
Person getChief();
Address getAddress();
}
RestaurantImpl.java:
package org.example;
public class RestaurantImpl implements Restaurant {
private String name;
private Person chief;
private Address address;
public RestaurantImpl(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getChief() {
return chief;
}
public void setChief(Person chief) {
this.chief = chief;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
RestaurantService.java:
package org.example;
public class RestaurantService {
public static void main(String[] args) {
Restaurant restaurant = getRestaurant();
// only the Getters are available
String name = restaurant.getName();
Address address = restaurant.getAddress();
Person chief = restaurant.getChief();
// This can not be avoided easily
if (restaurant instanceof RestaurantImpl) {
RestaurantImpl modifiableRestaurant = (RestaurantImpl) restaurant;
modifiableRestaurant.setName(name);
modifiableRestaurant.setAddress(address);
modifiableRestaurant.setChief(chief);
}
}
private static Restaurant getRestaurant() {
RestaurantImpl restaurant = new RestaurantImpl("My Restaurant Name");
restaurant.setAddress(new Address());
restaurant.setChief(new Person());
return restaurant;
}
}