迪米特法则,也称为最少知识原则(Law of Demeter),是面向对象设计中的一个原则,旨在降低对象之间的耦合性,提高系统的可维护性和可扩展性。该原则强调一个类不应该直接与其它不相关的类相互交互,而是通过少数几个密切相关的类来进行通信。这有助于减少类之间的依赖关系,降低代码的耦合性,使得系统更加灵活和易于维护。
迪米特法则的核心思想可以概括为以下几点:
一个对象应该尽量少地了解其他对象的内部结构和实现。
一个对象只与其直接朋友(即与其关联最密切的对象)进行交互。
避免在一个类中引入不必要的依赖关系,尽量保持类之间的解耦。
以下是一个示例代码来说明迪米特法则:
假设我们有一个电商系统,包含了顾客(Customer)、订单(Order)和商品(Product)这三个类。
- class Product {
- private String name;
- private double price;
-
- public Product(String name, double price) {
- this.name = name;
- this.price = price;
- }
-
- public double getPrice() {
- return price;
- }
- }
-
- class Order {
- private List
products = new ArrayList<>(); -
- public void addProduct(Product product) {
- products.add(product);
- }
-
- public double calculateTotalPrice() {
- double totalPrice = 0;
- for (Product product : products) {
- totalPrice += product.getPrice();
- }
- return totalPrice;
- }
- }
-
- class Customer {
- private List
orders = new ArrayList<>(); -
- public void addOrder(Order order) {
- orders.add(order);
- }
-
- public void printTotalSpent() {
- double totalSpent = 0;
- for (Order order : orders) {
- totalSpent += order.calculateTotalPrice();
- }
- System.out.println("Total amount spent: " + totalSpent);
- }
- }
在这个示例中,迪米特法则的考虑并不充分。例如,在Customer类的printTotalSpent方法中,我们直接访问了Order类的内部结构和Product类的内部结构。这会导致Customer类与Order类和Product类之间存在紧耦合的关系,违反了迪米特法则。
符合迪米特法则的改进示例:
- class Product {
- private String name;
- private double price;
-
- public Product(String name, double price) {
- this.name = name;
- this.price = price;
- }
-
- public double getPrice() {
- return price;
- }
- }
-
- class Order {
- private List
products = new ArrayList<>(); -
- public void addProduct(Product product) {
- products.add(product);
- }
-
- public double calculateTotalPrice() {
- double totalPrice = 0;
- for (Product product : products) {
- totalPrice += product.getPrice();
- }
- return totalPrice;
- }
- }
-
- class Customer {
- private List
orders = new ArrayList<>(); -
- public void addOrder(Order order) {
- orders.add(order);
- }
-
- public double calculateTotalSpent() {
- double totalSpent = 0;
- for (Order order : orders) {
- totalSpent += order.calculateTotalPrice();
- }
- return totalSpent;
- }
- }
-
- class ShoppingCart {
- private List
products = new ArrayList<>(); -
- public void addProduct(Product product) {
- products.add(product);
- }
-
- public double calculateTotalPrice() {
- double totalPrice = 0;
- for (Product product : products) {
- totalPrice += product.getPrice();
- }
- return totalPrice;
- }
- }
在改进后的示例中,Customer类不再直接与Order类和Product类的内部结构交互,而是通过添加一个calculateTotalSpent方法来计算总花费。同时,引入了ShoppingCart类来管理购物车中的商品,避免了Customer类与Product类的直接交互。