如何从Catalogue类而非Library类调用Customer类的方法
问题:从Catalogue类调用Customer类的方法
看起来你已经把Catalogue和Library关联起来了——Catalogue持有Library的引用,但因为Library里的customers是私有成员,所以没法直接从Catalogue访问Customer对象对吧?我给你几个可行的方案,都是基于保持封装性的前提来实现的:
先整理下你现有的代码(补全未完成部分)
Library类
import java.util.LinkedList; import java.util.List; public class Library { private Catalogue catalogue; private List<Customer> customers; public static void main(String[] args) { Library library = new Library(); } public Library() { catalogue = new Catalogue(this); customers = new LinkedList<Customer>(); } }
Catalogue类(补全构造方法)
public class Catalogue { private Library library; public Catalogue(Library library) { this.library = library; } }
解决方案
1. 给Library添加访问Customer的公共接口
既然customers是Library的私有成员,我们不能直接让Catalogue访问它,但可以在Library里提供必要的公共方法,让Catalogue通过持有的Library引用间接获取Customer对象,进而调用Customer的方法。
修改后的Library类:
import java.util.LinkedList; import java.util.List; import java.util.Optional; public class Library { private Catalogue catalogue; private List<Customer> customers; public static void main(String[] args) { Library library = new Library(); // 测试:添加一个客户 library.addCustomer(new Customer("C001", "张三")); // 让Catalogue调用Customer的方法 library.getCatalogue().showCustomerInfo("C001"); } public Library() { catalogue = new Catalogue(this); customers = new LinkedList<Customer>(); } // 方法1:根据ID查找客户(推荐,只暴露必要操作) public Optional<Customer> findCustomerById(String customerId) { return customers.stream() .filter(c -> c.getId().equals(customerId)) .findFirst(); } // 方法2:获取不可修改的客户列表(如果需要批量操作) public List<Customer> getCustomers() { return List.copyOf(customers); // 返回副本,避免外部修改内部状态 } // 辅助方法:添加客户(用于测试) public void addCustomer(Customer customer) { customers.add(customer); } // 获取Catalogue实例(用于测试) public Catalogue getCatalogue() { return catalogue; } }
2. 在Catalogue中通过Library引用调用Customer方法
现在Catalogue可以利用Library提供的方法拿到Customer对象,然后直接调用Customer的业务方法。
完善后的Catalogue类:
public class Catalogue { private Library library; public Catalogue(Library library) { this.library = library; } // 示例:调用Customer的getName和borrowBook方法 public void showCustomerInfo(String customerId) { library.findCustomerById(customerId).ifPresentOrElse( customer -> { System.out.println("客户姓名:" + customer.getName()); customer.borrowBook("B001"); // 调用Customer的借书方法 }, () -> System.out.println("未找到ID为" + customerId + "的客户") ); } }
3. 补全Customer类的必要方法
确保Customer类有你需要调用的方法,比如:
public class Customer { private String id; private String name; public Customer(String id, String name) { this.id = id; this.name = name; } // 基础get方法 public String getId() { return id; } public String getName() { return name; } // 业务方法示例:借书 public void borrowBook(String bookId) { System.out.println(name + "成功借阅书籍:" + bookId); } }
设计思路说明
- 保持封装性:没有直接暴露Library的私有成员
customers,而是通过公共接口提供必要的访问,避免外部类随意修改内部状态。 - 依赖合理:Catalogue作为Library的组成部分,通过持有的Library引用间接访问Customer,符合类之间的依赖关系。
内容的提问来源于stack exchange,提问作者Pramish Luitel
相关产品推荐
相关产品推荐

