Java七大设计原则(7/7)——迪米特法则

130 阅读2分钟

本文已参加「新人创作礼」活动,一起开启掘金创作之路。

定义

迪米特法则(Law of Demeter)又叫作最少知识原则(The Least Knowledge Principle),一个类对于其他类知道的越少越好,就是说一个对象应当对其他对象有尽可能少的了解,只和朋友通信,不和陌生人说话。

简而言之,就是与其他类交互越少越好,尽可能减少所受其他类的影响,降低耦合度。

代码实现

不使用迪米特法则

假设现在自己是Host,想玩英雄联盟了,没什么皮肤,想跟朋友John借个号爽爽。

定义John类

/**
 * @author John117
 * @date 2022/05/24  13:07
 */
public class John {
    Integer id = 114514;

    String password = "kksk";

    String  secret = "xxx";

    String address = "xxx";

    public Integer getId() {
        return id;
    }

    public String getPassword() {
        return password;
    }

    public String getSecret() {
        return secret;
    }

    public String getAddress() {
        return address;
    }

}

定义Host类

/**
 * @author John117
 * @date 2022/05/24  13:07
 */
public class Host {

    public void weGame(John john) {
        System.out.println("借到账号了:" + john.getId());

        System.out.println("也借到密码了:" + john.getPassword());
    }
    
}

测试

/**
 * @author John117
 * @date 2022/05/24  13:26
 */
public class Test {
    static John john = new John();

    public static void main(String[] args) {
        new Host().weGame(john);
    }

}

这么初看其实也没什么问题,但是仔细一看就会发现,这其实是违背了迪米特法则的。

本来只是想借个号,这种写法相当于把John搬到家里让他本人来输账号和密码。

一个类对于其他类知道的越少越好

这里的 weGame() 方法只需要接收 id 和 password,而不用接受整个John实体。

使用迪米特法则

John类如上,更改Host类

/**
 * @author John117
 * @date 2022/05/24  13:25
 */
public class Host {

    public void weGame(Integer id, String password) {
        System.out.println("借到账号了:" + id);

        System.out.println("也借到密码了:" + password);
    }
}

测试

/**
 * @author John117
 * @date 2022/05/24  13:28
 */
public class Test {

    static John john = new John();

    public static void main(String[] args) {
        // 在外面就将 id 和 password 拿到
        new Host().weGame(john.getId(), john.getPassword());
    }
}

这样就能减少了对John类的依赖,降低了耦合。